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 ⌀ |
|---|---|---|---|---|---|---|---|
662 | C | Binary Table | You are given a table consisting of $n$ rows and $m$ columns. Each cell of the table contains either $0$ or $1$. In one move, you are allowed to pick any row or any column and invert all values, that is, replace $0$ by $1$ and vice versa.
What is the minimum number of cells with value 1 you can get after applying some... | First let's examine a slow solution that works in $O(2^{n} \cdot m)$. Since each row can be either inverted or not, the set of options of how we can invert the rows may be encoded in a bitmask of length $n$, an integer from $0$ to $(2^{n} - 1)$, where the $i$-th bit is equal to 1 if and only if we invert the $i$-th r... | [
"bitmasks",
"brute force",
"divide and conquer",
"dp",
"fft",
"math"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
char s[100000];
int col[100000], dp[21][1 << 20];
int main() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
scanf(" %s", s);
for (int j = 0; j < m; j++) col[j] |= (s[j] - '0') << i;
}
for (int i = 0; i < m; i++) dp[... |
662 | D | International Olympiad | International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where $y$ stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string $y$ that has never been used before.... | Consider the abbreviations that are given to the first Olympiads. The first $10$ Olympiads (from year $1989$ to year $1998$) receive one-digit abbreviations ($IAO'9, IAO'0, ..., IAO'8$). The next $100$ Olympiads ($1999 - 2098$) obtain two-digit abbreviations, because all one-digit abbreviations are already taken, but t... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
char s[42];
int main() {
int n;
scanf("%d", &n);
while (n--) {
scanf(" %s", s);
int k = strlen(s + 4), year = atoi(s + 4), F = 0, tenPow = 10;
for (int i = 1; i < k; i++) {
F += tenPow;
tenPow *= 10;
... |
662 | E | To Hack or not to Hack | Consider a regular Codeforces round consisting of three problems that uses dynamic scoring.
You are given an almost final scoreboard. For each participant (including yourself), the time of the accepted submission for each of the problems is given. Also, for each solution you already know whether you are able to hack i... | Observation number one - as you are the only participant who is able to hack, the total score of any other participant cannot exceed $9000$ ($3$ problems for $3000$ points). Hence hacking at least $90$ solutions automatically guarantees the first place (the hacks alone increase the score by $9000$ points). Now we are l... | [
"brute force",
"dp",
"greedy"
] | 3,100 | #include<bits/stdc++.h>
#define time ololo
using namespace std;
int time[5000][3], n, solved[3], canHack[3], score[3], willHack[3], bestPlace, dp[2][90][90][90], ci, li;
int submissionScore(int sc, int tm) {
if (tm == 0) return 0;
return sc * (250 - abs(tm)) / 250;
}
int calcScore(int p) {
int sum = 0... |
663 | A | Rebus | You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer $n$. The goal is to replace each question mark with some positive integer from $1$ to $n$, such that equality holds. | First we check whether any solution exists at all. For that purpose, we calculate the number of positive (the first one and any other with the $+$ sign) and negative elements (with the $-$ sign) in the sum. Let them be $pos$ and $neg$, respectively. Then the minimum value of the sum that can be possibly obtained is equ... | [
"constructive algorithms",
"expression parsing",
"greedy",
"math"
] | 1,800 | #include<bits/stdc++.h>
using namespace std;
char s[100];
int main() {
int k = 0, n, pos = 1, neg = 0;
while (true) {
char c;
scanf(" %c", &c);
scanf(" %c", &c);
if (c == '=') break;
if (c == '+') pos++;
if (c == '-') neg++;
s[k++] = c;
}
sca... |
664 | A | Complicated GCD | Greatest common divisor $GCD(a, b)$ of two positive integers $a$ and $b$ is equal to the biggest integer $d$ such that both integers $a$ and $b$ are divisible by $d$. There are many efficient algorithms to find greatest common divisor $GCD(a, b)$, for example, Euclid algorithm.
Formally, find the biggest integer $d$, ... | We examine two cases: $a = b$ - the segment consists of a single number, hence the answer is $a$. $a < b$ - we have $gcd(a, a + 1, a + 2, ..., b) = gcd(gcd(a, a + 1), a + 2, ..., b) = gcd(1, a + 2, ..., b) = 1$. | [
"math",
"number theory"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
cin >> a >> b;
if (a == b) cout << a;
else cout << 1;
return 0;
} |
665 | A | Buses Between Cities | Buses run between the cities $A$ and $B$, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city $A$ departs every $a$ minutes and arrives to the city $B$ in a $t_{a}$ minutes, and a bus from the city $B$ departs every $b$ minutes and arrives to the city $A$ in a $t_{b}$ m... | Consider the time interval when Simion will be on the road strictly between cities $(x_{1}, y_{1})$ ($x_{1} = 60h + m, y_{1} = x_{1} + t_{a}$). Let's iterate over the oncoming buses. Let $(x_{2}, y_{2})$ be the time interval when the oncoming bus will be strictly between two cities. If the intersection of that interval... | [
"implementation"
] | 1,600 | int a, ta;
int b, tb;
int h, m;
bool read() {
if (!(cin >> a >> ta)) return false;
assert(cin >> b >> tb);
assert(scanf("%d:%d", &h, &m) == 2);
return true;
}
void solve() {
int x1 = h * 60 + m;
int y1 = x1 + ta;
int ans = 0;
for (int x2 = 5 * 60 + 0; x2 < 24 * 60; x2 += b) {
int y2 = x2 + tb;
int x = ma... |
665 | B | Shopping | Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online.
The store contains $k$ items. $n$ customers have already used the above service. Each user paid for $m$ items. Let $a_{ij}$ denote the $j$-th item in the $i$-th person's orde... | In this problem you should simply do what was written in the problem statement. There are no tricks. Complexity: $O(nmk)$. | [
"brute force"
] | 1,400 | const int N = 111;
int n, m, k;
int p[N];
int a[N][N];
bool read() {
if (!(cin >> n >> m >> k)) return false;
forn(i, k) {
assert(scanf("%d", &p[i]) == 1);
p[i]--;
}
forn(i, n)
forn(j, m) {
assert(scanf("%d", &a[i][j]) == 1);
a[i][j]--;
}
return true;
}
void solve() {
int ans = 0;
forn(i, n)
f... |
665 | C | Simple Strings | zscoder loves simple strings! A string $t$ is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.
zscoder is given a string $s$. He wants to change a minimum number of characters so that the string $s$ becomes simple. Help him with th... | There are two ways to solve this problem: greedy approach and dynamic programming. The first apprroach: Considerr some segment of consecutive equal characters. Let $k$ be the length of that segment. Easy to see that we should change at least $\textstyle{\left|{\frac{k}{2}}\right|}$ characters in the segment to remove a... | [
"dp",
"greedy",
"strings"
] | 1,300 | const int N = 1200300, A = 27;
int n;
char s[N];
bool read() {
if (!gets(s)) return false;
n = int(strlen(s));
return true;
}
int z[N][A];
int p[N][A];
char ans[N];
void solve() {
memset(z, 63, sizeof(z));
z[0][A - 1] = 0;
forn(i, n) {
int c = int(s[i] - 'a');
forn(j, A) {
int dv = z[i][j];
if (dv ... |
665 | D | Simple Subset | A tuple of positive integers ${x_{1}, x_{2}, ..., x_{k}}$ is called simple if for all pairs of positive integers $(i, j)$ ($1 ≤ i < j ≤ k$), $x_{i} + x_{j}$ is a prime.
You are given an array $a$ with $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$ (not necessary distinct). You want to find a simple subset of the arr... | Consider the subset $A$ that is the answer to the problem. Let $a, b, c$ be the arbitrary three elements from $A$ and let no more than one of them is equal to $1$. By the pigeonhole principle two of three elements from $a, b, c$ have the same parity. So we have two integers with even sum and only one of them is equal t... | [
"constructive algorithms",
"greedy",
"number theory"
] | 1,800 | const int N = 1010, X = 2100300;
int n, a[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) assert(scanf("%d", &a[i]) == 1);
return true;
}
int szp, p[X];
int mind[X];
void prepare() {
fore(i, 2, X) {
if (!mind[i]) {
p[szp++] = i;
mind[i] = i;
}
for (int j = 0; j < szp && p[j] <= mind[i] &... |
665 | E | Beautiful Subarrays | One day, ZS the Coder wrote down an array of integers $a$ with elements $a_{1}, a_{2}, ..., a_{n}$.
A subarray of the array $a$ is a sequence $a_{l}, a_{l + 1}, ..., a_{r}$ for some integers $(l, r)$ such that $1 ≤ l ≤ r ≤ n$. ZS the Coder thinks that a subarray of $a$ is beautiful if the bitwise xor of all the elemen... | The sign $\otimes$ is used for the binary operation for bitwise exclusive or. Let $s_{i}$ be the xor of the first $i$ elements on the prefix of $a$. Then the interval $(i, j]$ is beautiful if $s_{j}\otimes s_{i}\geq k$. Let's iterate over $j$ from $1$ to $n$ and consider the values $s_{j}$ as the binary strings. On eac... | [
"data structures",
"divide and conquer",
"strings",
"trees"
] | 2,100 | const int N = 1200300, LOGN = 30, V = N * LOGN;
int n, k;
int a[N];
bool read() {
if (!(cin >> n >> k)) return false;
forn(i, n) assert(scanf("%d", &a[i]) == 1);
return true;
}
int tsz;
int nt[V][2];
int cnt[V];
void clear() {
forn(i, V) {
nt[i][0] = nt[i][1] = -1;
cnt[i] = 0;
}
tsz = 1;
}
void add(int x... |
665 | F | Four Divisors | If an integer $a$ is divisible by another integer $b$, then $b$ is called the divisor of $a$.
For example: $12$ has positive $6$ divisors. They are $1$, $2$, $3$, $4$, $6$ and $12$.
Let’s define a function $D(n)$ — number of integers between $1$ and $n$ (inclusive) which has exactly four positive divisors.
Between $... | Easy to see that only the numbers of the form $p \cdot q$ and $p^{3}$ (for different prime $p, q$) have exactly four positive divisors. We can easily count the numbers of the form $p^{3}$ in $O(\lambda^{\underline{{{\mu}}}n})$, where $n$ is the number from the problem statement. Now let $p < q$ and $ \pi (k)$ be the nu... | [
"data structures",
"dp",
"math",
"number theory",
"sortings",
"two pointers"
] | 2,400 | li n;
bool read() {
return !!(cin >> n);
}
const int K = 10 * 1000 * 1000;
const int N = K;
const int P = 700100;
const int Q = 25 * 1000 * 1000;
int szp, p[P];
int mind[N];
void prepare() {
szp = 0;
forn(i, N) mind[i] = -1;
fore(i, 2, N) {
if (mind[i] == -1) {
assert(szp < P);
mind[i] = szp;
p[szp++... |
666 | A | Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know li... | This problem is solved with dynamic programming. We can select an arbitrary root of any length (at least five). Let's reverse the string. A boolean value $dp_{2, 3}[n]$ denotes if we could split a prefix of length $n$ to a strings of length 2 and 3 so that the last string has a corresponding length. Transitions: $d p_{... | [
"dp",
"implementation",
"strings"
] | 1,800 | null |
666 | B | World Tour | A famous sculptor Cicasso goes to a world tour!
Well, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country — Berland.
Cicasso is very devoted ... | You are given the oriented graph, find four distinct vertices $a, b, c, d$ such that each vertex if reachable from previous and the sum of shortest paths between consequitive vertices is as large as possible. First let's run a BFS from each vertex and find three most distant vertices over given graph and its reverse. A... | [
"graphs",
"shortest paths"
] | 2,000 | null |
666 | C | Codeword | The famous sculptor Cicasso is a Reberlandian spy!
These is breaking news in Berlandian papers today. And now the sculptor is hiding. This time you give the shelter to the maestro. You have a protected bunker and you provide it to your friend. You set the security system in such way that only you can open the bunker. ... | The first thing to notice: string itself does not matter, only its length does. In each sequence of length $n$ containing a fixed subsequence $s$ we can select $s$'s lexicographically minimal occurance, let it be $p_{1}, ..., p_{|s|}$. No character $s_{k + 1}$ may occur between $p_{k}$ and $p_{k + 1} - 1$, because othe... | [
"combinatorics",
"strings"
] | 2,500 | null |
666 | C | Codeword | The famous sculptor Cicasso is a Reberlandian spy!
These is breaking news in Berlandian papers today. And now the sculptor is hiding. This time you give the shelter to the maestro. You have a protected bunker and you provide it to your friend. You set the security system in such way that only you can open the bunker. ... | You are given four points on the plain. You should move each of them up, down, left, or right, such that the new configuration is a square with positive integer sides parallel to coordinate axes. Choose some $d$, length of the square side, and $(x, y)$, the position of the bottom-left point. A set from where to choose ... | [
"combinatorics",
"strings"
] | 2,500 | null |
666 | E | Forensic Examination | The country of Reberland is the archenemy of Berland. Recently the authorities of Berland arrested a Reberlandian spy who tried to bring the leaflets intended for agitational propaganda to Berland illegally . The most leaflets contain substrings of the Absolutely Inadmissible Swearword and maybe even the whole word.
B... | You are given string s and m strings ti. Queries of type ``find the string ti with number from [l;r] which has the largest amount of occurrences of substring s[a, b]'' approaching. Let's build segment tree over the texts t_i. In each vertex of segment tree let's build suffix automaton for the concatenation of texts fro... | [
"data structures",
"string suffix structures"
] | 3,100 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 5e4 + 42, logn = 20, sigma = 26;\n\nstring s[maxn];\n\nstruct suffix_automaton\n{\n\tvector<int> len, link, fpos, lpos, left, right, ans, max, cnt, st;\n\tvector<vector<int>> to;\n\tvector<vector<int>> up;\n\tstring s;\n\tint sz, last;\n\t\n\tvoid cl... |
667 | A | Pouring Rain | A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything h... | To know how much water you consume per second you should divide consumed volume, $v$, by the area of the cup, $\frac{\pi d^{2}}{4}$. Then you should compare thisit with $e$. If your speed of drinking is greater, then you'll drink all the water in $\frac{h}{\frac{4\upsilon}{\pi d^{2}}-e}$ seconds. Otherwise you would ne... | [
"geometry",
"math"
] | 1,100 | null |
667 | B | Coat of Anticubism | As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.
A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-d... | It is possible to make a convex polygon with given side lengths if and only if a generalized triangle inequality holds: the length of the longest side is less than the sum of lengths of other sides. It is impossible to make a convex polygon from a given set, so there is a side which is longest than (or equals to) than ... | [
"constructive algorithms",
"geometry"
] | 1,100 | null |
669 | A | Little Artem and Presents | Little Artem got $n$ stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Art... | It is obvious that we need to make sequence of moves like: 1, 2, 1, 2, ... So the answer is 2 * n / 3. After that we have either 0, 1 or 2 stones left. If we have 0, we are done, otherwise we have 1 or 2 left, so we only can give 1 more stone. Final formula is: (2 * n) / 3 + (n % 3 != 0 ? 1 : 0); | [
"math"
] | 800 | null |
670 | A | Holidays | On the planet Mars a year lasts exactly $n$ days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars. | There are many ways to solve this problem. Let's talk about one of them. At first we need to write a function, which takes the start day of the year and calculate the number of days off in such year. To make it let's iterate on the days of the year and will check every day - is it day off or no. It is easy to show that... | [
"brute force",
"constructive algorithms",
"greedy",
"math"
] | 900 | null |
670 | B | Game of Robots | In late autumn evening $n$ robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from $1$ to $10^{9}$.
At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identi... | To solve this problem we need to brute how many identifiers will called robots in the order from left to right. Let's solve this problem in one indexing. Let the current robot will call $i$ identifiers. If $k - i > 0$ let's make $k = k - i$ and go to the next robot. Else we need to print $a[k]$, where $a$ is the array ... | [
"implementation"
] | 1,000 | null |
670 | C | Cinema | Moscow is hosting a major international conference, which is attended by $n$ scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from $1$ to $10^{9}$.
In the evening after the conference, all $n$ scientists decid... | We need to use $map$ (let's call it $cnt$) and calculate how many scientists knows every language (i. e. $cnt[i]$ equals to the number of scientists who know the language number $i$). Let's use the pair $res$, where we will store the number of \textit{very pleased} scientists and the number of \textit{almost satisfied}... | [
"implementation",
"sortings"
] | 1,300 | null |
670 | D1 | Magic Powder - 1 | This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.
Waking up in the ... | This problem with small constraints can be solved in the following way. Let's bake cookies one by one until it is possible. For every new cookie let's calculate $val$ - how many grams of the magic powder we need to bake it. For this let's brute all ingredients and for the ingredient number $i$ if $a[i] \le b[i]$ let'... | [
"binary search",
"brute force",
"implementation"
] | 1,400 | null |
670 | D2 | Magic Powder - 2 | This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.
Waking up in the ... | Here we will use binary search on the answer. Let's we check the current answer equals to $cur$. Then the objective function must be realized in the following way. Let's store in the variable $cnt$ how many grams of the magic powder we need to bake $cur$ cookies. Let's iterate through the ingredients and the current in... | [
"binary search",
"implementation"
] | 1,500 | null |
670 | E | Correct Bracket Sequence Editor | Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, w... | Let's solve this problem in the following way. At first with help of stack let's calculate the array $pos$, where $pos[i]$ equals to the position of the bracket which paired for the bracket in the position $i$. Then we need to use two arrays $left$ and $right$. Then $left[i]$ will equals to the position of the closest ... | [
"data structures",
"dsu",
"strings"
] | 1,700 | null |
670 | F | Restore a Number | Vasya decided to pass a very large integer $n$ to Kate. First, he wrote that number as a string, then he appended to the right integer $k$ — the number of digits in $n$.
Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty s... | At first let's find the length of the Vasya's number. For make this let's brute it. Let the current length equals to $len$. Then if $len$ equals to the difference between the length of the given string and the number of digits in $len$ if means that $len$ is a length of the Vasya's number. Then we need to remove from t... | [
"brute force",
"constructive algorithms",
"strings"
] | 2,300 | null |
671 | A | Recycling Bottles | It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.
We can think Central Perk as coordinate plane. There are $n$ bottles on the ground, the $i$-th bottle is located at position $(x_{i}, y_{i})$. Both Adil an... | Let's solve the problem when Adil and Bera in the same coordinate with bin. Then answer will be $2\times\sum_{i=1}^{n}d i s t a n c e(B i n,B o t t l e_{i})$, let's say $T$ to this value. If Adil will take $i$-th bottle and Bera will take $j$-th bottle $(i \neq j)$, then answer will be $T + distance(Adil, Bottle_{i})... | [
"dp",
"geometry",
"greedy",
"implementation"
] | 1,800 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define pb push_back\n#define orta (bas + son >> 1)\n#define sag (k + k + 1)\n#define sol (k + k)\n#define endl '\\n'\n#define foreach(i,x) for(type(x)i=x.begin();i!=x.end();i++)\n#define FOR(ii,aa,bb) for(int ii=aa;ii<=bb;ii++)\n#define ROF(ii,aa,bb) for(int ii=aa;i... |
671 | B | Robin Hood | We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.
There are $n$ citizens in Kekoland, each person has $c_{i}$ coins. Each day, Robin Hood will take exactly $1$ coin from the richest person in the city and he will giv... | We observe that we can apply operations separately this means first we will apply all increase operations, and after will apply all decrease operations, vice versa. We will use following algorithm. We have to apply following operation $k$ times, add one to minimum number in array. We will simply binary search over mini... | [
"binary search",
"greedy"
] | 2,000 | "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define pii pair<int,int>\n#define ll long long\n#define N (int)(5e5+10)\n#define mod 1000000007\n#define mp make_pair\n#define pb push_back\n#define nd second\n#define st first\n#define inf mod\n#define endl '\\n'\n#define sag (sol|1)\n#define sol (root<<1)\n#define ... |
671 | C | Ultimate Weirdness of an Array | Yasin has an array $a$ containing $n$ integers. Yasin is a 5 year old, so he loves ultimate weird things.
Yasin denotes weirdness of an array as maximum $gcd(a_{i}, a_{j})$ value among all $1 ≤ i < j ≤ n$. For $n ≤ 1$ weirdness is equal to $0$, $gcd(x, y)$ is the greatest common divisor of integers $x$ and $y$.
He al... | If we calculate an array $H$ where $H_{i}$ is how many $(l - r)$s there are that $f(l, r)$ $ \le $ $i$, then we can easily calculate the answer. How to calculate array $H$. Let's keep a vector, $v_{i}$ keeps all elements indexes which contain $i$ as a divisor $-$ in sorted order. We will iterate over $max element$ to $... | [
"data structures",
"number theory"
] | 2,800 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define dbgs(x) cerr << (#x) << \" --> \" << (x) << ' '\n#define dbg(x) cerr << (#x) << \" --> \" << (x) << endl\n\n#define foreach(i,x) for(type(x)i=x.begin();i!=x.end();i++)\n#define FOR(ii,aa,bb) for(int ii=aa;ii<=bb;ii++)\n#define ROF(ii,aa,bb) for(int ii=aa;ii>=... |
671 | D | Roads in Yusland | Mayor of Yusland just won the lottery and decided to spent money on something good for town. For example, repair all the roads in the town.
Yusland consists of $n$ intersections connected by $n - 1$ bidirectional roads. One can travel from any intersection to any other intersection using only these roads.
There is on... | I want to thank GlebsHP, i originally came up with another problem similar to it, GlebsHP suggested to use this one in stead of it. Let's look for a optimal subset of paths, paths may intersect. To prevent from this let's change the problem litte bit. A worker can repair all nodes between $u_{i}$ and some $k$, where $k... | [
"data structures",
"dp",
"greedy"
] | 2,900 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define pb push_back\n#define orta (bas + son >> 1)\n#define sag (k + k + 1)\n#define sol (k + k)\n#define endl '\\n'\n#define foreach(i,x) for(type(x)i=x.begin();i!=x.end();i++)\n#define FOR(ii,aa,bb) for(int ii=aa;ii<=bb;ii++)\n#define ROF(ii,aa,bb) for(int ii=aa;i... |
671 | E | Organizing a Race | Kekoland is a country with $n$ beautiful cities numbered from left to right and connected by $n - 1$ roads. The $i$-th road connects cities $i$ and $i + 1$ and length of this road is $w_{i}$ kilometers.
When you drive in Kekoland, each time you arrive in city $i$ by car you immediately receive $g_{i}$ liters of gas. T... | Intended solution was $O(n{\sqrt{n}})$. Let $cost(l, r)$ be minimum cost to make $l$-$r$ suitable for a race. In task we have to find such $l$-$r$ that $cost(l, r)$ $ \le $ $k$ and $r$-$l$+$1$ is maximum. How to calculate $cost(l, r)$: Let's look at how we do our increases to make race from $l$ to $r$ (first stage) pos... | [
"data structures",
"greedy"
] | 3,300 | "#include <cstdio>\n#include <algorithm>\n#include <cassert>\n#include <tuple>\n#include <vector>\nusing namespace std;\n\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n\nconst int N = 100500;\nconst int K = 230;\n\ntypedef long long llong;\n\nint D[N];\nint A[N];\n\nllong PS[N];\nint st[N];\n\nbool was[N];\nvecto... |
672 | A | Summer Camp | Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with $1$ are written in one line. The prefix of these line is "123456789101112131415...". Your task is ... | This one is a simple brute force problem, we will construct our array. Adding numbers between $1$ and $370$ will be enough. After construction we just have to print $n$-th element of array. | [
"implementation"
] | 800 | null |
672 | B | Different is Good | A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string $s$ consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string $s$ to be distinct. Substring is a string formed by some ... | We observe that in a good string all letters must be different, because all substrings in size 1 must be different. So if size of string is greater than $26$ then answer must be $- 1$ since we only have 26 different letters. Otherwise, Let's suppose we have $k$ different letters in string sized $n$, in our string $k$ e... | [
"constructive algorithms",
"implementation",
"strings"
] | 1,000 | "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define pii pair<int,int>\n#define ll long long\n#define N (int)(1e5+10)\n#define mod 1000000007\n#define mp make_pair\n#define pb push_back\n#define nd second\n#define st first\n#define inf mod\n#define endl '\\n'\n#define sag (sol|1)\n#define sol (root<<1)\n#define ... |
673 | A | Bear and Game | Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts $90$ minutes and there are no breaks.
Each minute can be either interesting or boring. If $15$ consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be $n$ interesting minutes $t_{1}, t_{2}... | You are supposed to implement what is described in the statement. When you read numbers $t_{i}$, check if two consecutive numbers differ by more than $15$ (i.e. $t_{i} - t_{i - 1} > 15$). If yes then you should print $t_{i - 1} + 15$. You can assume that $t_{0} = 0$ and then you don't have to care about some corner cas... | [
"implementation"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int t[105];
int main() {
int n;
scanf("%d", &n);
t[0] = 0;
for(int i = 1; i <= n; ++i)
scanf("%d", &t[i]);
t[n+1] = 91;
for(int i = 1; i <= n + 1; ++i) {
if(t[i] > t[i-1] + 15) {
printf("%d\n", t[i-1] + 15);
return 0;
}
}
puts("90");
return 0;
} |
673 | B | Problems for Round | There are $n$ problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are $m$ pairs of similar problems. Authors want to split problems between two division according to the following rules:
- Problemset of... | Some prefix of problems must belong to one division, and the remaining suffix must belong to the other division. Thus, we can say that we should choose the place (between two numbers) where we split problems. Each pair $a_{i}, b_{i}$ (let's say that $a_{i} < b_{i}$) means that the splitting place must be between $a_{i}... | [
"greedy",
"implementation"
] | 1,300 | #include<bits/stdc++.h>
using namespace std;
int main() {
int n, m;
scanf("%d%d", &n, &m);
int low = 1, high = n;
while(m--) {
int a, b;
scanf("%d%d", &a, &b);
if(a > b) swap(a, b);
low = max(low, a);
high = min(high, b);
}
printf("%d\n", max(0, high - low... |
675 | A | Infinite Sequence | Vasya likes everything infinite. Now he is studying the properties of a sequence $s$, such that its first element is equal to $a$ ($s_{1} = a$), and the difference between any two neighbouring elements is equal to $c$ ($s_{i} - s_{i - 1} = c$). In particular, Vasya wonders if his favourite integer $b$ appears in this s... | Firstly, in case $c = 0$ we should output YES if $a = b$ else answer is NO. If $b$ belongs to sequence $b = a + k * c$ where k is non-negative integer. So answer is YES if $(b - a) / c$ is non-negative integer else answer is NO. | [
"math"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
if (c == 0) {
if (a == b) cout << "YESn";
else cout << "NOn";
} else {
if ((b - a) % c == 0 && (b - a) / c >= 0) cout << "YESn";
else cout << "NOn";
}
} |
675 | B | Restoring Painting | Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it.
- The painting is a square $3 × 3$, each cell contains a single integer from $1$ to $n$... | x a y b m c z d w Number in the center may be any from 1 to $n$ because number in the center belongs to all subsquares $2 \times 2$. So, let's find answer with fixed number in the center and then multiply answer by $n$. Let's iterate over all possible $x$. Sums of each subsquare $2 \times 2$ are the same so $x + b ... | [
"brute force",
"constructive algorithms",
"math"
] | 1,400 | #include <iostream>
using namespace std;
int main() {
int n, a, b, c, d;
cin >> n >> a >> b >> c >> d;
long long ans = 0;
for (int x = 1; x <= n; x++) {
int y = x + b - c;
int z = x + a - d;
int w = a + y - d;
if (1 <= y && y <= n && 1 <= z && z <= n && 1 <= w && w <= ... |
675 | C | Money Transfers | There are $n$ banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than $1$. Also, bank $1$ and bank $n$ are neighbours if $n > 1$. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative,... | We have array $a_{i}$ and should make all numbers in it be equal to zero with minimal number of operations. Sum of all $a_{i}$ equals to zero. We can divide array into parts of consecutive elements with zero sum. If part has length $l$ we can use all pairs of neighbours in operations and make all numbers be equal to ze... | [
"constructive algorithms",
"data structures",
"greedy",
"sortings"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int n;
cin >> n;
map<long long, int> d;
long long sum = 0;
int ans = n - 1;
for (int i = 0; i < n; i++) {
int t;
cin >> t;
sum += t;
d[sum]++;
a... |
675 | D | Tree Construction | During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.
You are given a sequence $a$, consisting of $n$ \textbf{distinct} integers, that is used to construct the binary search tree. Below is... | We have binary search tree (BST) and should insert number in it with good time complexity. Let we should add number $x$. Find numbers $l < x < r$ which were added earlier, $l$ is maximal possible, $r$ is minimal possible (all will be similar if only one of this numbers exists). We can find them for example with std::se... | [
"data structures",
"trees"
] | 1,800 | #include <iostream>
#include <set>
#include <map>
using namespace std;
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
set<int> numbers;
map<int, int> left;
map<int, int> right;
int n, v;
cin >> n >> v;
numbers.insert(v);
for (int i = 0; i < n - 1; i++) {
cin >> v;... |
675 | E | Trains and Statistic | Vasya commutes by train every day. There are $n$ train stations in the city, and at the $i$-th station it's possible to buy only tickets to stations from $i + 1$ to $a_{i}$ inclusive. No tickets are sold at the last station.
Let $ρ_{i, j}$ be the minimum number of tickets one needs to buy in order to get from stations... | Let the indexation will be from zero. So we should subtract one from all $a_{i}$. Also let $a_{n - 1} = n - 1$. $dp_{i}$ is sum of shortests pathes from $i$ to $i + 1... n - 1$. $dp_{n - 1} = 0$ $dp_{i} = dp_{m} - (a_{i} - m) + n - i - 1$ where $m$ belongs to range from $i + 1$ to $a_{i}$ and $a_{m}$ is maximal. We can... | [
"data structures",
"dp",
"greedy"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1 << 18;
pair<int, int> tree[maxn * 2];
void build(const vector<int> &a, int n) {
for (int i = 0; i < n; i++) tree[maxn + i] = {a[i], i};
for (int i = maxn - 1; i > 0; i--)
tree[i] = max(tree[i * 2], tree[i * 2 + 1]);
}
int get(int l, in... |
676 | A | Nicholas and Permutation | Nicholas has an array $a$ that contains $n$ \textbf{distinct} integers from $1$ to $n$. In other words, Nicholas has a permutation of size $n$.
Nicholas want the minimum element (integer $1$) and the maximum element (integer $n$) to be as far as possible from each other. He wants to perform exactly one swap in order t... | All what you need to solve this problem - find the positions of numbers $1$ and $n$ in the given array. Let's this positions equal to $p_{1}$ and $p_{n}$, then the answer is the maximum of 4 values: $abs(n - p_{1}), abs(n - p_{n}), abs(1 - p_{1}), abs(1 - p_{n}).$ Asymptotic behavior $O(n)$. | [
"constructive algorithms",
"implementation"
] | 800 | null |
676 | B | Pyramid of Glasses | Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is $n$. The top level consists of only $1$ glass, that stands on $2$ glasses on the second lev... | The restrictions in this problem allow to simulate the process. Let the volume of one wineglass equals to $2^{n}$ conventional units. So the volume of the champagne surpluses which will stream to bottom level will always integer number. So let's pour in the top wineglass $q * 2^{n}$ units of champagne, and then we have... | [
"implementation",
"math"
] | 1,500 | null |
676 | C | Vasya and String | High school student Vasya got a string of length $n$ as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a \textbf{substring} (consecutive subsequence) consisting of equal letters.
Vasya can change no more than $k$ characters of the origi... | This problem can be solved with help of two pointers. Let the first pointer is $l$ and the second pointer is $r$. Then for every position $l$ we will move right end $r$ until on the substring $s_{l}s_{l + 1}... s_{r}$ it is possible to make no more than $k$ swaps to make this substring beautiful. Then we need to update... | [
"binary search",
"dp",
"strings",
"two pointers"
] | 1,500 | null |
676 | D | Theseus and labyrinth | Theseus has just arrived to Crete to fight Minotaur. He found a labyrinth that has a form of a rectangular field of size $n × m$ and consists of blocks of size $1 × 1$.
\textbf{Each} block of the labyrinth has a button that rotates \textbf{all} blocks $90$ degrees clockwise. Each block rotates around its center and do... | It is easy to understand that we have only 4 states of the maze. How to solve this problem if there is no any buttons? It is just bfs on the maze (on the graph). Because of buttons we need to add to graph 3 additional levels and add edges between this levels. After that we need to run bfs on this graph and find the len... | [
"graphs",
"implementation",
"shortest paths"
] | 2,000 | null |
676 | E | The Last Fight Between Human and AI | 100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.
The following game was chosen for the fights: initially there is a polynom... | In this problem we have two main cases: $k = 0, k \neq 0$. Case when $k = 0$. Then the division of the polynomial to the $x - k$ depends only of the value of $a_{0}$. If $a_{0}$ is already known then we need to compare it with zero. If $a_{0} = 0$ then the human wins, otherwise the human loses. If $a_{i}$ is not kno... | [
"math"
] | 2,400 | null |
677 | A | Vanya and Fence | Vanya and his friends are walking along the fence of height $h$ and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed $h$. If the height of some person is greater than $h$ he can bend down and then he surely won't be noticed by the guard. The height ... | For each friend we can check, if his height is more than $h$. If it is, then his width is $2$, else $1$. Complexity $O(n)$. | [
"implementation"
] | 800 | #include <iostream>
using namespace std;
typedef long long ll;
ll i,n,h,ans,x;
int main()
{
cin >> n >> h;
ans = n;
for (i = 0; i < n; i++)
{
cin >> x;
ans += (x>h);
}
cout << ans << endl;
return 0;
}
|
677 | B | Vanya and Food Processor | Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed $h$ and the processor smashes $k$ centimeters of potato each second. If there are less than $k$ centimeters remaining, than during this second processor smashes all the remaining potato.
V... | The solution, that does same thing, as in the problem statement will fail with TL, because if the height of each piece of potato will be $10^{9}$ and smashing speed will be $1$, then for each piece we will do $10^{9}$ operations. With each new piece of potato $a_{i}$ we will smash the potato till $a[i]$ $MOD$ $k$, so w... | [
"implementation",
"math"
] | 1,400 | #include <iostream>
#include <stdio.h>
using namespace std;
typedef long long ll;
ll i,n,h,ans,x,cur_h,k;
int main()
{
cin >> n >> h >> k;
ans = 0;
cur_h = 0;
for (i = 0; i < n; i++)
{
scanf("%I64d", &x);
if (cur_h + x <= h)
cur_h += x;
else
ans++, cur_h = x;
ans += cur_h/k;
cur_h %= k;
}
ans +... |
677 | C | Vanya and Label | While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used $&$ as a bitwise AND for these two words represented as a integers in base $64$ and got new word. Now Vanya thinks of some string $s$ and wants to know the number of pairs of words of length $|s|$ (length of $s$), such that... | We can transform our word in binary notation, we can do it easily, because $64 = 2^{6}$. Move through the bits of this number: if bit is equal to $0$, then we can have 3 different optinos of this bit in our pair of words: 0&1, 1&0, 0&0, else we can have only one option: 1&1. So the result will be $3^{nullbits}$, where ... | [
"bitmasks",
"combinatorics",
"implementation",
"strings"
] | 1,500 | #include <iostream>
#include <stdio.h>
#include <string>
#define MOD 1000000007
using namespace std;
typedef long long ll;
ll i,j,n,h,ans,x,cur_h,k;
string s;
string pattern;
ll symbol_val[305];
int main()
{
cin >> s;
for (char i = '0'; i <= '9'; i++)
pattern.push_back(i);
for (char i = 'A'; i <= 'Z'; i++)
patte... |
677 | D | Vanya and Treasure | Vanya is in the palace that can be represented as a grid $n × m$. Each room contains a single chest, an the room located in the $i$-th row and $j$-th columns contains the chest of type $a_{ij}$. Each chest of type $x ≤ p - 1$ contains a key that can open any chest of type $x + 1$, and all chests of type $1$ are not loc... | We can make dynamic programming $dp[col][row]$, where $dp[col][row]$ is minimal time, that we have waste to open the chest in the cell $(col, row)$. For the cells of color $1$: $dp[x][y] = x + y$. For each next color $color$ we can look over all cells of color $color - 1$ and all cells of color $color$, then for each c... | [
"data structures",
"dp",
"graphs",
"shortest paths"
] | 2,300 | #include <iostream>
#include <stdio.h>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>
#define MOD 1000000007
#define N 512
#define mp make_pair
#define X first
#define Y second
using namespace std;
typedef int ll;
ll i,j,n,h,x,y,glob,k,m,p,fx,fy;
ll a[505][505], dp[505][505], d[505][505], t[4... |
677 | E | Vanya and Balloons | Vanya plays a game of balloons on the field of size $n × n$, where each cell contains a balloon with one of the values $0$, $1$, $2$ or $3$. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:
... | For each cell $(x, y)$ take the maximum possible cross with center in this cell, that doesn't contains zeros. To do it fast, we can make arrays of partial sums for all possible $8$ directions, in which each cell will contain the number of non-zero balloons in each direction. For example, if we want to know, how many no... | [
"binary search",
"brute force",
"dp",
"implementation"
] | 2,300 | #include <iostream>
#include <stdio.h>
#include <string>
#include <cmath>
#define MOD 1000000007
#define N 2005
using namespace std;
typedef unsigned int ll;
ll i,j,n,h,x,y,cur_h,k,dir;
ll pre[8][N][N];
double sums[8][N][N],ans,logs[N][N],lg2,lg3;
ll ansx,ansy,anssize,ansdir;
ll total;
ll directions[8][2] = {{-1,-1},{-... |
678 | A | Johny Likes Numbers | Johny likes numbers $n$ and $k$ very much. Now Johny wants to find the smallest integer $x$ greater than $n$, so it is divisible by the number $k$. | We should find minimal $x$, so $x \cdot k > n$. Easy to see that $x=\lfloor{\frac{n}{k}}\rfloor+1$. To learn more about floor/ceil functions I reccomend the book of authors Graham, Knuth, Patashnik "Concrete Mathematics". There is a chapter there about that functions and their properties. Complexity: $O(1)$. | [
"implementation",
"math"
] | 800 | li n, k;
bool read() {
return !!(cin >> n >> k);
}
void solve() {
cout << (n / k + 1) * k << endl;
} |
678 | B | The Same Calendar | The girl Taylor has a beautiful calendar for the year $y$. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
The calendar is so beautiful that she wants to know what is the next year after $y$ when the calendar will be exactly the same. Help ... | Two calendars are same if and only if they have the same number of days and starts with the same day of a week. So we should simply iterate over years and maintain the day of a week of January, 1st (for example). Easy to see that the day of a week increases by one each year except of the leap years, when it increases b... | [
"implementation"
] | 1,600 | int y;
bool read() {
return !!(cin >> y);
}
bool leap(int y) {
return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0);
}
void solve() {
bool is_leap = leap(y);
int d = 0;
do {
d++;
if (leap(y)) d++;
y++;
d %= 7;
} while (d || leap(y) != is_leap);
cout << y << endl;
} |
678 | C | Joty and Chocolate | Little Joty has got a task to do. She has a line of $n$ tiles indexed from $1$ to $n$. She has to paint them in a strange pattern.
An unpainted tile should be painted Red if it's index is divisible by $a$ and an unpainted tile should be painted Blue if it's index is divisible by $b$. So the tile with the number divisi... | Easy to see that we can paint with both colours only tiles with the numbers multiple of $lcm(a, b)$. Obviously that tiles should be painted with more expensive colour. So the answer equals to $\bar{\cal J}\left|\frac{\bar{\eta}}{\bar{u}}\right|\downarrow\left(\left|\frac{\bar{\eta}}{b}\right|=\bar{\cal H}\langle\bar{\e... | [
"implementation",
"math",
"number theory"
] | 1,600 | li n, a, b, p, q;
bool read() {
return !!(cin >> n >> a >> b >> p >> q);
}
li gcd(li a, li b) { return !a ? b : gcd(b % a, a); }
li lcm(li a, li b) { return a / gcd(a, b) * b; }
void solve() {
li ans = 0;
ans += (n / a) * p;
ans += (n / b) * q;
ans -= (n / lcm(a, b)) * min(p, q);
cout << ans << endl;
} |
678 | D | Iterated Linear Function | Consider a linear function $f(x) = Ax + B$. Let's define $g^{(0)}(x) = x$ and $g^{(n)}(x) = f(g^{(n - 1)}(x))$ for $n > 0$. For the given integer values $A$, $B$, $n$ and $x$ find the value of $g^{(n)}(x)$ modulo $10^{9} + 7$. | The problem can be solved using closed formula: it's need to calculate the sum of geometric progression. The formula can be calculated using binary exponentiation. I'll describe more complicated solution, but it's more general. If we have a set of variables and at each step all variables are recalculating from each oth... | [
"math",
"number theory"
] | 1,700 | int A, B, x;
li n;
bool read() {
return !!(cin >> A >> B >> n >> x);
}
const int mod = 1000 * 1000 * 1000 + 7;
inline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }
inline int mul(int a, int b) { return int(a * 1ll * b % mod); }
inline void inc(int& a, int b) { a = add(a, b); }
void mul(int a... |
678 | E | Another Sith Tournament | The rules of Sith Tournament are well known to everyone. $n$ Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each... | Let's solve the problem using dynamic programming. $z_{mask, i}$ - the maximal probability of Ivans victory if the siths from the $mask$ already fought and the $i$-th sith left alive. To calculate that DP we should iterate over the next sith (he will fight against the $i$-th sith): $z_{m a s k,i}=m a x_{j=1,j\not\in m ... | [
"bitmasks",
"dp",
"math",
"probabilities"
] | 2,200 | const int N = 20, EXPN = (1 << 18) + 3;
int n;
ld p[N][N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) forn(j, n) assert(cin >> p[i][j]);
return true;
}
ld z[EXPN][N];
ld solve(int mask, int i) {
ld& ans = z[mask][i];
if (ans > -0.5) return ans;
if (mask == (1 << n) - 1) return ans = !i;
ans = 0;... |
678 | F | Lena and Queries | Lena is a programmer. She got a task to solve at work.
There is an empty set of pairs of integers and $n$ queries to process. Each query is one of three types:
- Add a pair $(a, b)$ to the set.
- Remove a pair added in the query number $i$. All queries are numbered with integers from $1$ to $n$.
- For a given integer... | Let's interpret the problem geometrically: the pairs from the set are the lines and the problem to find to topmost intersection of the vertical line with the lines from the set. Let's split the queries to $\sqrt{n}$ blocks. Consider the lines added before the current block and that will not deleted in the current block... | [
"data structures",
"divide and conquer",
"geometry"
] | 2,500 | const int N = 300300;
int n;
int t[N], a[N], b[N], id[N], q[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) {
assert(scanf("%d", &t[i]) == 1);
if (t[i] == 1) {
assert(scanf("%d%d", &a[i], &b[i]) == 2);
} else if (t[i] == 2) {
assert(scanf("%d", &id[i]) == 1);
id[i]--;
} else if (t[i] ==... |
679 | A | Bear and Prime 100 | \textbf{This is an interactive problem. In the output section below you will see the information about flushing the output.}
Bear Limak thinks of some hidden number — an integer from interval $[2, 100]$. Your task is to say if the hidden number is prime or composite.
Integer $x > 1$ is called prime if it has exactly ... | If a number is composite then it's either divisible by $p^{2}$ for some prime $p$, or divisible by two distinct primes $p$ and $q$. To check the first condition, it's enough to check all possible $p^{2}$ (so, numbers $4$, $9$, $25$, $49$). If at least one gives "yes" then the hidden number if composite. If there are tw... | [
"constructive algorithms",
"interactive",
"math"
] | 1,400 | from sys import stdout
PRIMES = [x for x in range(2,100) if 0 not in [x%i for i in range(2,x)]]
NORMAL = PRIMES[:15]
SQUARES = [x*x for x in PRIMES[:4]]
for ele in SQUARES:
print(ele)
stdout.flush()
x = input()
if x == "yes":
print("composite")
exit(0)
yes = 0
for ele in NORMAL:
... |
679 | B | Bear and Tower of Cubes | Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side $a$ has volume $a^{3}$. A tower consisting of blocks with sides $a_{1}, a_{2}, ..., a_{k}$ has the total volume $a_{... | Let's find the maximum $a$ that $a^{3} \le m$. Then, it's optimal to choose $X$ that the first block will have side $a$ or $a - 1$. Let's see why. We want to first maximize the number of blocks we can get with new limit $m_{2}$. Secondarily, we want to have the biggest initial $X$. You can analyze the described above... | [
"binary search",
"dp",
"greedy"
] | 2,200 | #include "bits/stdc++.h"
using namespace std;
#define ll long long
vector <ll> X;
map <ll, pair <int, ll> > M;
pair <int, ll> go(ll x)
{
if(x <= 1)
return {x,x};
if(M.find(x) != M.end())
return M[x];
int i = upper_bound(X.begin(), X.end(), x) - X.begin() - 1;
int p1, p2;
long long q1, q2;
tie(p1... |
679 | C | Bear and Square Grid | You have a grid with $n$ rows and $n$ columns. Each cell is either empty (denoted by '.') or blocked (denoted by 'X').
Two empty cells are directly connected if they share a side. Two cells $(r_{1}, c_{1})$ (located in the row $r_{1}$ and column $c_{1}$) and $(r_{2}, c_{2})$ are connected if there exists a sequence of... | Let's first find CC's (connected components) in the given grid, using DFS's. We will consider every possible placement of a $k \times k$ square. When the placement is fixed then the answer is equal to the sum of $k^{2}$ the the sum of sizes of CC's touching borders of the square (touching from outside), but for those... | [
"dfs and similar",
"dsu",
"implementation"
] | 2,400 | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
impo... |
679 | D | Bear and Chase | Bearland has $n$ cities, numbered $1$ through $n$. There are $m$ bidirectional roads. The $i$-th road connects two distinct cities $a_{i}$ and $b_{i}$. No two roads connect the same pair of cities. It's possible to get from any city to any other city (using one or more roads).
The distance between cities $a$ and $b$ i... | Check my code below, because it has a lot of comments. First, in $O(n^{3})$ or faster find all distances between pairs of cities. Iterate over all $g1$ - the first city in which you use the BCD. Then, for iterate over all $d1$ - the distance you get. Now, for all cities calculate the probability that Limak will be ther... | [
"brute force",
"dfs and similar",
"graphs",
"implementation",
"math",
"probabilities"
] | 2,900 | #include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)
typedef double T;
const int nax = 1005;
int dist[nax][nax];
vector<int> w[nax];
T p_later[nax]; // p[v] - probability for city v in the second day
T p_dist_max[nax];
bool vis[nax];
void max_self(T & a, T b) {
a = max(a, b)... |
679 | E | Bear and Bad Powers of 42 | Limak, a bear, isn't good at handling queries. So, he asks you to do it.
We say that powers of $42$ (numbers $1, 42, 1764, ...$) are bad. Other numbers are good.
You are given a sequence of $n$ good integers $t_{1}, t_{2}, ..., t_{n}$. Your task is to handle $q$ queries of three types:
- 1 i — print $t_{i}$ in a sep... | The only special thing in numbers $1, 42, ...$ was that there are only few such numbers (in the possible to achieve range, so up to about $10^{14}$). Let's first solve the problem without queries "in the interval change all numbers to x". Then, we can make a tree with operations (possible with lazy propagation): In a t... | [
"data structures"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
int n, q;
vector <long long> poty;
int n1;
long long inf=(long long)1000000000*1000000000;
long long narz[1000007];
int czybom[1000007];
long long bom[1000007];
long long maxd[1000007];
long long mind[1000007];
long long zos[1000007];
int typ, p1, p2, p3;
inline int... |
680 | A | Bear and Five Cards | A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.
Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.
He is allowed to \textbf{at most once} discard two or three... | Iterate over all pairs and triples of numbers, and for each of them check if all two/three numbers are equal. If yes then consider the sum of remaining numbers as the answer (the final answer will be the minimum of considered sums). Below you can see two ways to implement the solution. | [
"constructive algorithms",
"implementation"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int main() {
int t[5];
for(int i = 0; i < 5; ++i)
scanf("%d", &t[i]);
sort(t, t + 5);
int best_remove = 0;
for(int i = 0; i < 5; ++i) {
if(i + 1 < 5 && t[i] == t[i+1])
best_remove = max(best_remove, 2 * t[i]);
if(i + 2 < 5 && t[i] == t[i+2])
best_remove = ma... |
680 | B | Bear and Finding Criminals | There are $n$ cities in Bearland, numbered $1$ through $n$. Cities are arranged in one long row. The distance between cities $i$ and $j$ is equal to $|i - j|$.
Limak is a police officer. He lives in a city $a$. His job is to catch criminals. It's hard because he doesn't know in which cities criminals are. Though, he k... | Limak can't catch a criminal only if there are two cities at the same distance and only one of them contains a criminal. You should iterate over the distance and for each distance $d$ check if $a - d$ and $a + d$ are both in range $[1, n]$ and if only one of them has $t_{i} = 1$. | [
"constructive algorithms",
"implementation"
] | 1,000 | #include<bits/stdc++.h>
using namespace std;
const int nax = 1005;
int t[nax];
bool impossible[nax];
int main() {
int n, a;
scanf("%d%d", &n, &a);
for(int i = 1; i <= n; ++i)
scanf("%d", &t[i]);
for(int i = 1; i <= n; ++i)
for(int j = i + 1; j <= n; ++j)
if(abs(i - a) == abs(j - a) && t[i] != t[j]) {
// ... |
681 | A | A Good Contest | Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to $2400$; it is orange if his rating is less than $2400$ but greater or equal to $2200$, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.
Anton wants the color... | If for any participant $before_{i} \ge 2400$ and $after_{i} > before_{i}$, then the answer is "YES", otherwise "NO" | [
"implementation"
] | 800 | "#include <iostream>\n\nusing namespace std;\n\nconst int RED = 2400;\n\nint main() {\n int n;\n cin >> n;\n bool good = false;\n for (int i = 0; i < n; i++) {\n string handle;\n int before, after;\n cin >> handle >> before >> after;\n if (before >= RED && after > before) {\n ... |
681 | B | Economy Game | Kolya is developing an economy simulator game. His most favourite part of the development process is in-game testing. Once he was entertained by the testing so much, that he found out his game-coin score become equal to $0$.
Kolya remembers that at the beginning of the game his game-coin score was equal to $n$ and tha... | We can simply try every $a$ from $0$ to $n / 1234567$ and $b$ from $0$ to $n / 123456$, and if $n - a * 1234567 - b * 123456$ is non-negative and divided by $1234$, then the answer is "YES". If there is no such $a$ and $b$, then the answer is "NO". | [
"brute force"
] | 1,300 | "#include <iostream>\n\nusing namespace std;\n\nint main() {\n int n;\n cin >> n;\n for (int a = 0; a <= n; a += 1234567) {\n for (int b = 0; b <= n - a; b += 123456) {\n if ((n - a - b) % 1234 == 0) {\n cout << \"YES\";\n return 0;\n }\n }\n ... |
681 | C | Heap Operations | Petya has recently learned data structure named "Binary heap".
The heap he is now operating with allows the following operations:
- put the given number into the heap;
- get the value of the minimum element in the heap;
- extract the minimum element from the heap;
Thus, at any moment of time the heap contains severa... | Let's solve this problem with greedy approach. Let's apply operations from log in given order. If current operation is $insert$ $x$, then add element $x$ to heap. If current operation is $removeMin$, then if heap is not empty, then simply remove minimal element, otherwise if heap is empty, add operation $insert$ $x$, w... | [
"constructive algorithms",
"data structures",
"greedy"
] | 1,600 | "#include <iostream>\n#include <queue>\n#include <string>\n\nusing namespace std;\n\nconst int NO_X = 2e9;\n\nconst string REMOVE = \"removeMin\";\nconst string GET = \"getMin\";\nconst string INSERT = \"insert\";\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n\n int n;\n cin >> n;\n\n ... |
681 | D | Gifts by the List | Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are $n$ men in Sasha's family, so let's number them with integers from $1$ to $n$.
Each man has at most one father but may have arbitrary number of sons.
Man number $A$ is conside... | Formal statement of the problem: You have a directed acyclic graph, every vertex has at most one ingoing edge. Vertex $A$ is an ancestor of vertex $B$ if there is a path from $A$ to $B$ in graph. Also every vertex is an ancestor of itself. Every vertex $i$ has a pair - vertex $a_{i}$, $a_{i}$ - ancestor of $i$. You nee... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"trees"
] | 2,000 | "#include <iostream>\n#include <vector>\n#include <memory.h>\n\nusing namespace std;\n\nconst int MAX_N = (int) 1e5;\n\nvector<int> g[MAX_N];\nint a[MAX_N];\nbool inA[MAX_N];\n\nvector<int> ts;\nbool used[MAX_N];\n\nvoid dfs1(int v) {\n if (used[v]) {\n return;\n }\n used[v] = true;\n for (int i = 0;... |
681 | E | Runaway to a Shadow | Dima is living in a dormitory, as well as some cockroaches.
At the moment $0$ Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly $T$ seconds for aiming, and after that he will precisely strike the cockroach and finish it.
To survive the cockroach has to run into a shadow, cast by round... | At first assume the case when cockroach at the moment $0$ is already inside or on the border of some circle. In that case the cockroach will always survive, i. e. the probability is $1$. Otherwise the cockroach will have time to run to every point inside the circle with center of $x_{0}$, $y_{0}$ and radius $v \times ... | [
"geometry",
"sortings"
] | 2,500 | "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nconst double eps = 1e-9;\n\ndouble sqrDist(double x1, double y1, double x2, double y2) {\n return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n}\n\ndouble dist(double x1, double y1, double x2, double y2) {\n... |
682 | A | Alyona and Numbers | After finishing eating her bun, Alyona came up with two integers $n$ and $m$. She decided to write down two columns of integers — the first column containing integers from $1$ to $n$ and the second containing integers from $1$ to $m$. Now the girl wants to count how many pairs of integers she can choose, one from the f... | Let's iterate over the first number of the pair, let it be $x$. Then we need to count numbers from $1$ to $m$ with the remainder of dividing $5$ equal to $(5 - xmod5)mod$ 5. For example, you can precalc how many numbers from $1$ to $m$ with every remainder between $0$ and $4$. | [
"constructive algorithms",
"math",
"number theory"
] | 1,100 | null |
682 | B | Alyona and Mex | Someone gave Alyona an array containing $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular,... | Let's sort the array. Let $cur =$ 1. Then walk through the array. Let's look at current number. If it is greater or equal to $cur$, then let's increase $cur$ by $1$. Answer is $cur$. | [
"sortings"
] | 1,200 | null |
682 | C | Alyona and the Tree | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex $1$, every vertex and every edge of which has a number written on.
The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call v... | Let's do dfs. Suppose that we now stand at the vertex $u$. Let $v$ be some ancestor of vertex $u$. Then $dist(v, u) = dist(1, u) - dist(1, v)$. If $dist(v, u) > a_{u}$, then the vertex $u$ makes $v$ sad. So you must remove the whole subtree of vertex $u$. Accordingly, it is possible to maintain a minimum among $dist(1,... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | 1,600 | null |
682 | D | Alyona and Strings | After returned from forest, Alyona started reading a book. She noticed strings $s$ and $t$, lengths of which are $n$ and $m$ respectively. As usual, reading bored Alyona and she decided to pay her attention to strings $s$ and $t$, which she considered very similar.
Alyona has her favourite positive integer $k$ and bec... | Let's use the method of dynamic programming. Let d[i][j][cnt][end] be answer to the problem for the prefix of string $s$ of length $i$ and for the prefix of string $t$ of length $j$, we have chosen $cnt$ substrings. $end = 1$, if both last characters of the prefixes are included in the maximum subsequence and $end = 0$... | [
"dp",
"strings"
] | 1,900 | null |
682 | E | Alyona and Triangles | You are given $n$ points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these $n$ points, which area exceeds $S$.
Alyona tried to construct a triangle with integer coordinates, which contains all $n$ points and which area doesn't exceed $4S$, but... | Let's find the triangle with maximum area among all triangles whose vertices belong to the set of points. (For $N^{2}$ with the convex hull and the two pointers). We can prove that if we take the triangle, whose vertices are the midpoints of the sides of the triangle with maximum area, the area of such a triangle is no... | [
"geometry",
"two pointers"
] | 2,600 | null |
685 | A | Robbers' watch | Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches.
First, as they know that kingdom police is bad at math, robbers use the positional numeral system \textbf{with base $7$}. Second, they divide one da... | In this problem we use the septimal number system. It is a very important limitation. Let's count how many digits are showed on the watch display and call it $cnt$. If $cnt$ more than $7$, the answer is clearly $0$ (because of pigeonhole principle). If $cnt$ is not greater than $7$, then you can just bruteforces all ca... | [
"brute force",
"combinatorics",
"dp",
"math"
] | 1,700 | BASE = 7
def itov(x):
digits = []
if x == 0:
digits.append(0)
while x > 0:
digits.append(x % BASE)
x //= BASE
digits.reverse()
return digits
def gen(pos = 0, minute = False, smaller = False):
max_val = max_minute if minute else max_hour
if pos >= len(max_val):
... |
685 | B | Kay and Snowflake | After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.
Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of $n$ nodes. The root of tree has index $1$. Kay is very interes... | cdkrot There are many possible approaches. Solution by cdkrot: Look at the all candidates for the centroid of the vertices $v$ subtree. The size of centroid subtree must be at least $\textstyle{\frac{1}{2}}$ of the vertex $v$ subtree size. (If it isn't, then after cutting the upper part will have too big size) Choose t... | [
"data structures",
"dfs and similar",
"dp",
"trees"
] | 1,900 | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <cassert>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <cmath>
#include <bitset>
#pragma comment... |
685 | C | Optimal Point | When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.
Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is bl... | Let's say few words about ternary search. It works correctly, but too slow. It's complexity is $O(n\log^{3}v)$, where $n = 10^{5}$, and $v = 10^{18}$. Don't use it. Solution. 1) Let's make binary search on answer 2) Consider areas of "good" points (with dist $ \le mid$) for each source point. 3) Intersect those areas ... | [
"binary search",
"math"
] | 2,900 | // Copyright (C) 2016 Sayutin Dmitry.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; version 3
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... |
685 | D | Kay and Eternity | Snow Queen told Kay to form a word "eternity" using pieces of ice. Kay is eager to deal with the task, because he will then become free, and Snow Queen will give him all the world and a pair of skates.
Behind the palace of the Snow Queen there is an infinite field consisting of cells. There are $n$ pieces of ice sprea... | Let's solve this problem with scanline. Go through all rows from left to right and maintain the array in which in $j$ index we will store the number of points in a square with bottom left coordinate $(i, j)$, where i is current row of scanline. This takes $O(MAXCORD^{2})$ time. Note that the set of squares that contain... | [
"brute force",
"implementation",
"sortings"
] | 2,600 | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <cassert>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <cmath>
#include <bitset>
#pragma comment... |
685 | E | Travelling Through the Snow Queen's Kingdom | Gerda is travelling to the palace of the Snow Queen.
The road network consists of $n$ intersections and $m$ bidirectional roads. Roads are numbered from $1$ to $m$. Snow Queen put a powerful spell on the roads to change the weather conditions there. Now, if Gerda steps on the road $i$ at the moment of time less or equ... | We propose following solution: Let's solve task with divide & conquer. At first let's lift $l$ to the first index, where $s$ was mentioned And lower the $r$ to the last index, where $t$ was mentioned. This will not affect answers, but will make implementation much more easy. Let's look on all queries. For each query co... | [
"bitmasks",
"brute force",
"divide and conquer",
"graphs"
] | 2,800 | // Copyright (C) 2016 Sayutin Dmitry.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; version 3
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRA... |
686 | A | Free Ice Cream | After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have $x$ ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the... | You just needed to implement the actions described in statement. If you solution failed, then you probably forgot to use 64-bit integers or made some small mistake. | [
"constructive algorithms",
"implementation"
] | 800 | import sys
def main():
n, answer = map(int, sys.stdin.readline().split())
sad = 0
for i in range(n):
type_of, cur = sys.stdin.readline().split()
cur = int(cur)
if type_of == "+":
answer += cur
elif answer >= cur:
answer -= cur
else:
... |
686 | B | Little Robber Girl's Zoo | Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She ... | We need to sort an array with strange operations - namely, to swap elements with even and odd indices in subarray of even length. Note that we can change the 2 neighboring elements, simply doing our exchange action for subarray of length $2$ containing these elements. Also, note that $n \le 100$, and it is permission... | [
"constructive algorithms",
"implementation",
"sortings"
] | 1,100 | n = int(input())
arr = list(map(int, input().split()))
for i in range(n - 1, 0, -1):
for j in range(i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
print(j + 1, j + 2) |
687 | A | NP-Hard Problem | Recently, Pari and Arya did some research about NP-Hard problems and they found the \underline{minimum vertex cover} problem very interesting.
Suppose the graph $G$ is given. Subset $A$ of its vertices is called a \underline{vertex cover} of this graph, if for each edge $uv$ there is at least one endpoint of it in thi... | Try to use all of the vertices. Then look at the two vertex covers together in the graph and see how it looks like. Looking at the two vertex covers in the graph, you see there must be no edge $uv$ that $u$ and $v$ are in the same vertex cover. So the two vertex covers form a bipartition of the graph, so the graph have... | [
"dfs and similar",
"graphs"
] | 1,500 | // . .. ... .... ..... be name khoda ..... .... ... .. . \\
#include <bits/stdc++.h>
using namespace std;
inline int in() { int x; scanf("%d", &x); return x; }
const int N = 120021;
vector <int> vc[2];
vector <int> g[N];
int mark[N];
bool dfs(int v, int color = 2)
{
mark[v] = color;
vc[color - 1].push_ba... |
687 | B | Remainders Game | Today Pari and Arya are playing a game called Remainders.
Pari chooses two positive integer $x$ and $k$, and tells Arya $k$ but not $x$. Arya have to find the value $x\ {\mathrm{mod}}\ k$. There are $n$ ancient numbers $c_{1}, c_{2}, ..., c_{n}$ and Pari has to tell Arya $x\ \mathrm{mod}\ c_{i}$ if Arya wants. Given $... | Assume the answer of a test is No. There must exist a pair of integers $x_{1}$ and $x_{2}$ such that both of them have the same remainders after dividing by any $c_{i}$, but they differ in remainders after dividing by $k$. Find more facts about $x_{1}$ and $x_{2}$! Consider the $x_{1}$ and $x_{2}$ from the hint part. W... | [
"chinese remainder theorem",
"math",
"number theory"
] | 1,800 | // . .. ... .... ..... be name khoda ..... .... ... .. . \\
#include <bits/stdc++.h>
using namespace std;
inline int in() { int x; scanf("%d", &x); return x; }
const long long N = 1200021;
int cntP[N], isP[N];
int main()
{
for(int i = 2; i < N; i++)
if(!isP[i])
for(int j = i; j < N; j += i)
isP[j... |
687 | C | The Values You Can Make | Pari wants to buy an expensive chocolate from Arya. She has $n$ coins, the value of the $i$-th coin is $c_{i}$. The price of the chocolate is $k$, so Pari will take a subset of her coins with sum equal to $k$ and give it to Arya.
Looking at her coins, a question came to her mind: after giving the coins to Arya, what v... | Use dynamic programming. Let $dp_{i, j, k}$ be true if and only if there exists a subset of the first $i$ coins with sum $j$, that has a subset with sum $k$. There are 3 cases to handle: The $i$-th coin is not used in the subsets. The $i$-th coin is used in the subset to make $j$, but it's not used in the subset of thi... | [
"dp"
] | 1,900 | // - -- --- ---- -----be name khoda----- ---- --- -- - \\
#include <bits/stdc++.h>
using namespace std;
inline int in() { int x; scanf("%d", &x); return x; }
const int N = 505;
bool dp[2][N][N];
int main()
{
int n, k;
cin >> n >> k;
dp[0][0][0] = 1;
for(int i = 1; i <= n; i++)
{
int now = i % 2;
int ... |
687 | D | Dividing Kingdom II | Long time ago, there was a great kingdom and it was being ruled by The Great Arya and Pari The Great. These two had some problems about the numbers they like, so they decided to divide the great kingdom between themselves.
The great kingdom consisted of $n$ cities numbered from $1$ to $n$ and $m$ bidirectional roads b... | Consider the following algorithm to answer a single query: Sort the edges and add them one by one to the graph in decreasing order of their weights. The answer is weight of the first edge, which makes an odd cycle in the graph. Now show that there are only $O(n)$ effective edges, which removing them may change the answ... | [
"brute force",
"data structures",
"dsu",
"graphs",
"sortings"
] | 2,500 | // . .. ... .... ..... be name khoda ..... .... ... .. . \\
#include <bits/stdc++.h>
using namespace std;
inline int in() { int x; scanf("%d", &x); return x; }
const int N = 2002, M = (1 << 20), Q = 1001, S = 2 * M;
#define rank PAP
struct Edge
{
int u, v, w;
Edge(int u = 0, int v = 0, int w = 0):v(v), ... |
687 | E | TOF | Today Pari gave Arya a cool graph problem. Arya wrote a non-optimal solution for it, because he believes in his ability to optimize non-optimal solutions. In addition to being non-optimal, his code was buggy and he tried a lot to optimize it, so the code also became dirty! He keeps getting Time Limit Exceeds and he is ... | Looking at the code in the statement, you can see only the first edge in neighbors of each node is important. So for each vertex with at least one outgoing edge, you have to choose one edge and ignore the others. After this the graph becomes in the shape of some cycles with possible branches, and some paths. The number... | [
"dfs and similar",
"graphs"
] | 2,900 | // . .. ... .... ..... be name khoda ..... .... ... .. . \\
#include <bits/stdc++.h>
using namespace std;
inline int in() { int x; scanf("%d", &x); return x; }
const int N = 5005;
int comp[N], bfsDist[N], bfsPar[N];
vector <int> g[N], gR[N];
bool mark[N], inCycle[N];
bool dfs(int v, vector <int> *g, vecto... |
688 | A | Opponents | Arya has $n$ opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Ar... | Let's find out for each row of the given matrix if it is completely consisting of ones or not. Make another array $canWin$, and set $canWin_{i}$ equal to one if the $i$-th row consists at least one zero. Then the problem is to find the maximum subsegment of $canWin$ array, consisting only ones. It can be solved by find... | [
"implementation"
] | 800 | n, d = map(int, raw_input().split())
cur = 0
ans = 0
for i in range(d):
s = raw_input()
if (s == '1' * n):
cur = 0
else:
cur += 1
ans = max(ans, cur)
print ans |
688 | B | Lovely Palindromes | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example $12321$, $100001$ and $1$ are palindrome numbers, while $112$ and $1021$ are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behin... | Try to characterize even-length palindrome numbers. For simplifications, in the following solution we define lovely integer as an even-length positive palindrome number. An even-length positive integer is lovely if and only if the first half of its digits is equal to the reverse of the second half. So if $a$ and $b$ ar... | [
"constructive algorithms",
"math"
] | 1,000 | s = raw_input()
print s + ''.join(reversed(s)) |
689 | A | Mike and Cellphone | While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:
\begin{center}
$\frac{1}{\left|\begin{array}{l l}{1\prod2\... | We can try out all of the possible starting digits, seeing if we will go out of bounds by repeating the same movements. If it is valid and different from the correct one, we output "NO", otherwise we just output "YES". | [
"brute force",
"constructive algorithms",
"implementation"
] | 1,400 | n = int(raw_input())
s = raw_input()
a = []
for i in range(10):
a.append(True)
for i in range(n):
c = int(s[i])
a[c] = False
inc = 0
if a[1] and a[2] and a[3]:
inc = -3
if a[7] and a[9] and a[0]:
inc = +3
if a[1] and a[4] and a[7] and a[0]:
inc = -1
if a[3] and a[6] and a[9] and a[0]:
inc = +1
if inc == 0:
prin... |
689 | B | Mike and Shortcuts | Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of $n$ intersections numbered from $1$ to $n$. Mike starts walking from his house located at the intersection number $1$ and goes along some sequence of intersections.... | We can build a complete graph where the cost of going from point $i$ to point $j$ if $|i - j|$ if $a_{i}! = j$ and $1$ if $a_{i} = j$.The we can find the shortest path from point 1 to point $i$.One optimisation is using the fact that there is no need to go from point $i$ to point $j$ if $j \neq s[i]$,$j \neq i - 1$... | [
"dfs and similar",
"graphs",
"greedy",
"shortest paths"
] | 1,600 | import Queue
n = int(raw_input())
a = raw_input().split(' ')
used = []
d = []
for i in range(0, n):
used.append(False)
d.append(-1)
q = Queue.Queue()
q.put(0)
d[0] = 0
while not(q.empty()):
v = q.get()
for dl in range(-1, +2):
u = v + dl
if 0 <= u and u < n and d[u] == -1:
d[... |
689 | C | Mike and Chocolate Thieves | Bad news came to Mike's village, some thieves stole a bunch of chocolates from the local factory! Horrible!
Aside from loving sweet things, thieves from this area are known to be very greedy. So after a thief takes his number of chocolates for himself, the next thief will take exactly $k$ times more than the previous ... | Suppose we want to find the number of ways for a fixed $n$. Let $a, b, c, d$ ( $0 < a < b < c < d \le n$ ) be the number of chocolates the thieves stole. By our condition, they have the form $b = ak, c = ak^{2}, d = ak^{3}$,where $k$ is a positive integer. We can notice that $2\leq k\leq{\sqrt{\frac{n}{a}}}\leq{\sqrt... | [
"binary search",
"combinatorics",
"math"
] | 1,700 |
# include <bits/stdc++.h>
using namespace std;
long long get(long long n)
{
long long ans = 0;
for (long long i = 2; i * i * i <= n;++i)
ans += n / (1ll*i * i * i);
return ans;
}
int main()
{
long long m,n=-1;
cin>>m;
long long l=0,r=5e15;
while (l<r)
{
long long ... |
689 | D | Friends and Subsequences | Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows?
Every one of them has an integer sequences $a$ and $b$ of length $n$. Being given a query of the form of pair of integers ... | First of all it is easy to see that if we fix $l$ then have $\operatorname*{m}_{i=l}^{r}a_{i}-\operatorname*{min}_{i=l}b_{i}\leq\operatorname*{max}_{i=l}a_{i}-\operatorname*{min}_{i=l}b_{i}$. So we can just use binary search to find the smallest index $r_{min}$ and biggest index $r_{max}$ that satisfy the equality and ... | [
"binary search",
"data structures"
] | 2,100 |
#include <bits/stdc++.h>
using namespace std;
const int N = int(1e6) + 5;
int a[N], b[N], n;
int lfa[N], rga[N], lfb[N], rgb[N], nxt[N];
void calc_max(int *a, int *lf, int *rg) {
stack <int> st;
a[n] = int(1e9) + 1;
for (int i = 0; i <= n; ++i) {
while (!st.empty() && a[st.top()] < a[i]) {
rg[st.top()] = i;... |
689 | E | Mike and Geometry Problem | Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define $f([l, r]) = r - l + 1$ to be the number of integer points in the segment $[l, r]$ with $l ≤ r$ (say that $f({\mathcal{O}})=0$). You are given two integers $n$ and $k$ and $n$ closed interva... | Let define the following propriety:if the point $i$ is intersected by $p$ segments then in our sum it will be counted $\scriptstyle{\binom{p}{k}}$ times,so our task reduce to calculate how many points is intersected by $i$ intervals $1 \le i \le n$.Let $dp[i]$ be the number of points intersected by $i$ intervals.Th... | [
"combinatorics",
"data structures",
"dp",
"geometry",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
#define ll long long
#define ld long double
using namespace std;
const int mod = 1e9+7;
ll pp(ll x, int y)
{
if (!y) return 1;
ll t = pp(x,y/2);
t = 1ll*t*t;
t%=mod;
if (y%2) t*=1ll*x;
t%=mod;
return t;
}
int n,k;
struct s
{
int x;
int y;
};
s a[2*200000];
ll c[200001];
void g... |
691 | A | Fashion in Berland | According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with $n$ buttons. Determine if it is fast... | In this problem you should simply check the conditions from the problem statement. Complexity: $O(n)$. | [
"implementation"
] | 1,000 | const int N = 1010;
int n, a[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) assert(cin >> a[i]);
return true;
}
void solve() {
int cnt = accumulate(a, a + n, 0);
if (n == 1) puts(cnt == 1 ? "YES" : "NO");
else puts(cnt == n - 1 ? "YES" : "NO");
} |
691 | B | s-palindrome | Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half.
\begin{center}
{\small English alphabet}
... | In this problem you should simply find the symmetric letters by picture and also observe that the pairs $(b, d)$ and $(p, q)$ is the symmteric reflections. Complexity: $O(n)$. | [
"implementation",
"strings"
] | 1,600 | string s;
bool read() {
return !!getline(cin, s);
}
string symmetric = "AHIMOoTUVvWwXxY";
map<char, char> opposite = {{'p', 'q'}, {'q', 'p'}, {'d', 'b'}, {'b', 'd'}};
void solve() {
forn(i, sz(s)) {
if (symmetric.find(s[i]) != string::npos) {
if (s[sz(s) - 1 - i] != s[i]) {
puts("NIE");
return;
}
... |
691 | C | Exponential notation | You are given a positive decimal number $x$.
Your task is to convert it to the "simple exponential notation".
Let $x = a·10^{b}$, where $1 ≤ a < 10$, then in general case the "simple exponential notation" looks like "aEb". If $b$ equals to zero, the part "Eb" should be skipped. If $a$ is an integer, it should be writ... | This is an implementation problem. You should do exactly what is written in the problem statement. On my mind the simplest way is to find the position of the first not zero digit and the position of the dot. The difference between that positions is the value of $b$ (if the value is positive you should also decrease it ... | [
"implementation",
"strings"
] | 1,800 | string s;
bool read() {
return !!getline(cin, s);
}
void solve() {
int pos = int(find_if(all(s), [](char c) { return c != '0' && c != '.'; }) - s.begin());;
size_t dot_pos = s.find('.');
if (dot_pos == string::npos) {
dot_pos = s.size();
} else {
s.erase(dot_pos, 1);
}
int expv = (int) dot_pos - pos;
if ... |
691 | D | Swaps in Permutation | You are given a permutation of the numbers $1, 2, ..., n$ and $m$ pairs of positions $(a_{j}, b_{j})$.
At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?
Let $p$ and $q$ be two permutations of the numbers $... | Consider a graph with $n$ vertices whose edges is the pairs from the input. It's possible to swap any two values with the positions in some connected component in that graph. So we can sort the values from any component in decreasing order. Easy to see that after sorting the values of each component we will get the lex... | [
"dfs and similar",
"dsu",
"math"
] | 1,700 | const int N = 1200300;
int n, m;
int p[N];
pti a[N];
bool read() {
if (!(cin >> n >> m)) return false;
forn(i, n) {
assert(scanf("%d", &p[i]) == 1);
p[i]--;
}
forn(i, m) {
assert(scanf("%d%d", &a[i].x, &a[i].y) == 2);
a[i].x--, a[i].y--;
}
return true;
}
bool used[N];
vector<int> g[N];
vector<int> perm... |
691 | E | Xor-sequences | You are given $n$ integers $a_{1}, a_{2}, ..., a_{n}$.
A sequence of integers $x_{1}, x_{2}, ..., x_{k}$ is called a "xor-sequence" if for every $1 ≤ i ≤ k - 1$ the number of ones in the binary representation of the number $x_{i}$ $\otimes$ $x_{i + 1}$'s is a multiple of $3$ and $x_{i}\in\{a_{1},a_{2},\ldots,a_{n}\}$ ... | Let $z_{ij}$ be the number of xor-sequences of length $i$ with the last element equal to $a_{j}$. Let $g_{ij}$ be equal to one if $a_{i}\otimes a_{j}$ contains the number of ones in binary presentation that is multiple of three. Otherwise let $g_{ij}$ be equal to zero. Consider a vectors $z_{i} = {z_{ij}}$, $z_{i - 1} ... | [
"matrices"
] | 1,900 | const int N = 101;
int n;
li k;
li a[N];
bool read() {
if (!(cin >> n >> k)) return false;
forn(i, n) assert(cin >> a[i]);
return true;
}
const int mod = 1000 * 1000 * 1000 + 7;
inline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }
inline void inc(int& a, int b) { a = add(a, b); }
inline in... |
691 | F | Couple Cover | Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with $n$ balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) — the num... | Let's count the number of pairs with multiple less than $p$. To get the number of not less pairs we should sumply subtract from $n \cdot (n - 1)$ the number of less pairs. Let $cnt_{i}$ be the number of values in $a$ equal to $i$ and $z_{j}$ be the number of pairs from $a$ with the multiple equal to $j$. To calculate t... | [
"brute force",
"dp",
"number theory"
] | 2,200 | const int N = 3100300;
int n, m;
int a[N], p[N];
bool read() {
if (!(cin >> n)) return false;
forn(i, n) assert(scanf("%d", &a[i]) == 1);
assert(cin >> m);
forn(i, m) assert(scanf("%d", &p[i]) == 1);
return true;
}
int cnt[N];
li z[N];
void solve() {
memset(cnt, 0, sizeof(cnt));
forn(i, n) cnt[a[i]]++;
fo... |
696 | A | Lorenzo Von Matterhorn | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections $i$ and $2i$ and another road between $i$ and $2i + 1$ for every positive integer $i$. You can clearly see that there exists a unique shortest path betwe... | Do what problem wants from you. The only thing is to find the path between the two vertices (or LCA) in the tree. You can do this in $O(l g(n))$ since the height of the tree is $O(l g(n))$. You can keep edge weights in a map and get/set the value whenever you want. Here's a code for LCA: LCA(v, u): while v != u: if dep... | [
"brute force",
"data structures",
"implementation",
"trees"
] | 1,500 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
696 | B | Puzzles | Barney lives in country USC (United States of Charzeh). USC has $n$ cities numbered from $1$ through $n$ and $n - 1$ roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number $1$. Thus if one will start his journey from city $1$, he can visi... | First of all $starting_time$ of a vertex is the number of dfs calls before the dfs call of this vertex plus 1. Now suppose we want to find the answer for vertex $v$. For any vertex $u$ that is not in subtree of $v$ and is not an ancestor $v$, denote vertices $x$ and $y$ such that: $x \neq y$ $x$ is an ancestor of $v$... | [
"dfs and similar",
"math",
"probabilities",
"trees"
] | 1,700 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.