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 number of operations?
|
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 row. Each column also represents a bitmask of length $n$ (the bits correspond to the values of that row in each of the $n$ rows). Let the bitmask of the $i$-th column be $col_{i}$, and the bitmask of the inverted rows be $mask$. After inverting the rows the $i$-th column will become $(c o l_{i}\oplus m a s k)$. Suppose that $(c o l_{i}\oplus m a s k)$ contains $k=p o p_{-}c o u n t(c o l_{i}\oplus m a s k)$ ones. Then we can obtain either $k$ or $(n - k)$ ones in this column, depending on whether we invert the $i$-th column itself. It follows that for a fixed bitmask $mask$ the minimum possible number of ones that can be obtained is equal to $\sum_{i=1}^{m}\operatorname*{min}(p o p_{-}c o u n t(c o l_{i}\oplus m a s k),n-p o p_{-}c o u n t(c o l_{i}\oplus m a s k))$. Now we want to calculate this sum faster than $O(m)$. Note that we are not interested in the value of the mask $(c o l_{i}\oplus m a s k)$ itself, but only in the number of ones it contains (from $0$ to $n$). Therefore we may group the columns by the value of $p o p_{-}c o u n t(c o l_{i}\oplus m a s k)$. Let $dp[k][mask]$ be the number of such $i$ that $p o p_{-}c o u n t(c o l_{i}\oplus m a s k)=k$, then for a fixed bitmask $mask$ we can calculate the sum in $O(n)$ - $\sum_{k=0}^{n}\operatorname*{min}(k,n-k)\cdot d p[k][m a s k]$. What remains is to calculate the value of $dp[k][mask]$ in a quick way. As the name suggests, we can use dynamic programming for this purpose. The value of $dp[0][mask]$ can be found in $O(m)$ for all bitmasks $mask$: each column $col_{i}$ increases $dp[0][col_{i}]$ by 1. For $k > 0$, $col_{i}$ and $mask$ differ in exactly $k$ bits. Suppose $mask$ and $col_{i}$ differ in position $p$. Then $col_{i}$ and $(m a s k\oplus p)$ differ in exactly $(k - 1)$ bits. The number of such columns is equal to $d p[k-1][m a s k\oplus p]$, except we counted in also the number of columns $col_{i}$ that differ with $(m a s k\oplus p)$ in bit $p$ (thus, $mask$ and $col_{i}$ have the same value in bit $p$). Thus we need to subtract $dp[k - 2][mask]$, but again, except the columns among these that differ with $mask$ in bit $p$. Let $n e x t=(m a s k\oplus p)$; by expanding this inclusion-exclusion type argument, we get that the number of masks we are interested in can be expressed as $dp[k - 1][next] - dp[k - 2][mask] + dp[k - 3][next] - dp[k - 4][mask] + dp[k - 5][next] - ...$. By summing all these expressions for each bit $p$ from $0$ to $n$, we get $dp[k][mask] \cdot k$, since each column is counted in $k$ times (for each of the bits $p$ where the column differs from $mask$). Therefore, we are now able to count the values of $dp[k][mask]$ in time $O(2^{n} \cdot n^{3})$ using the following recurrence: $d p[k][m a s k]={\frac{1}{k}}\sum_{p=0}^{n-1}\sum_{f=1}^{k}(-1)^{f-1}\cdot\,d p[k-f][m a s k\oplus(2^{p}\cdot\,(f\mod2))]$ This is still a tad slow, but we can speed it up to $O(2^{n} \cdot n^{2})$, for example, in a following fashion: $\sum_{p=0}^{n-1}\sum_{f=3}^{k}(-1)^{f-1}\,\cdot\,\,d p[k-f][m a s k\,\oplus\,(2^{p}\,\cdot\,(f\mathrm{\boldmath~\mod~2)})$ $=(k-2)\cdot d p[k-2][m a s k]$ $d p[k][m a s k]=\frac{1}{k}((k-2-n)\cdot d p[k-2][m a s k]+\sum_{p=0}^{n-1}d p[k-1][m a s k\oplus2^{p}])$
|
[
"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[0][col[i]]++;
for (int k = 1; k <= n; k++)
for (int mask = 0; mask < (1 << n); mask++) {
int sum = k > 1 ? (k - 2 - n) * dp[k - 2][mask] : 0;
for (int p = 0; p < n; p++) sum += dp[k - 1][mask ^ (1 << p)];
dp[k][mask] = sum / k;
}
int ans = n * m;
for (int mask = 0; mask < (1 << n); mask++) {
int cnt = 0;
for (int k = 0; k <= n; k++) cnt += min(k, n - k) * dp[k][mask];
ans = min(ans, cnt);
}
printf("%d\\n", ans);
return 0;
}
|
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. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.
For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.
You are given a list of abbreviations. For each of them determine the year it stands for.
|
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 the last two digits of $100$ consecutive integers are pairwise different. Similarly, the next $1000$ Olympiads get three-digit abbreviations and so on. Now examine the inversed problem (extract the year from an abbreviation). Let the abbreviation have $k$ digits, then we know that all Olympiads with abbreviations of lengths $(k - 1), (k - 2), ..., 1$ have passed before this one. The number of such Olympiads is $10^{k - 1} + 10^{k - 2} + ... + 10^{1} = F$ and the current Olympiad was one of the $10^{k}$ of the following. Therefore this Olympiad was held in years between $(1989 + F)$ and $(1989 + F + 10^{k} - 1)$. As this segment consists of exactly $10^{k}$ consecutive natural numbers, it contains a single number with a $k$-digit suffix that matches the current abbreviation. It is also the corresponding year.
|
[
"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;
}
while (year < 1989 + F) year += tenPow;
printf("%d\\n", year);
}
return 0;
}
|
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 it or not. The only changes in the scoreboard that will happen before the end of the round are your challenges.
What is the best place you may take at the end?
More formally, $n$ people are participating (including yourself). For any problem, if it was solved by exactly $k$ people at the end of the round, the maximum score for this problem is defined as:
- If $n < 2k ≤ 2n$, then the maximum possible score is $500$;
- If $n < 4k ≤ 2n$, then the maximum possible score is $1000$;
- If $n < 8k ≤ 2n$, then the maximum possible score is $1500$;
- If $n < 16k ≤ 2n$, then the maximum possible score is $2000$;
- If $n < 32k ≤ 2n$, then the maximum possible score is $2500$;
- If $32k ≤ n$, then the maximum possible score is $3000$.
Let the maximum possible score for some problem be equal to $s$. Then a contestant who didn't manage to get it accepted (or his solution was hacked) earns $0$ points for this problem. If he got the the solution accepted $t$ minutes after the beginning of the round (and his solution wasn't hacked), he earns $\frac{s\cdot(250-t)}{250}$ points for this problem.
The overall score of a participant is equal to the sum of points he earns for each problem plus $100$ points for each successful hack (only you make hacks).
The resulting place you get is equal to one plus the number of participants who's overall score is strictly greater than yours.
|
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 left with the problem where the number of hacks we make is at most $90$. We can try each of the $6^{3}$ possible score assignments for the problems in the end of the round. As we know the final score for each problem, we can calculate the maximum number of hacks we are allowed to make so the problem gets the assigned score. This is also the exact amount of hacks we will make in that problem. As we know the number of hacks we will make, we can calculate our final total score. Now there are at most $90$ participants who we can possibly hack. We are interested only in those who are on top of us. By hacking we want to make their final score less than that of us. This problem can by solved by means of dynamic programming: $dp[p][i][j][k]$ - the maximum number of participants among the top $p$, whom we can push below us by hacking first problem $i$ times, second problem $j$ times and third problem $k$ times. The recurrence: we pick a subset of solutions of the current participant that we will hack, and if after these hacks we will push him below us, we update the corresponding dp state. For example, if it is enough to hack the first and the third problems, then $dp[p + 1][i + 1][j][k + 1] = max(dp[p + 1][i + 1][j][k + 1], dp[p][i][j][k] + 1)$
|
[
"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;
for (int i = 0; i < 3; i++) sum += submissionScore(score[i], time[p][i]);
return sum;
}
int countHacks(int p) {
int cnt = 0;
for (int i = 0; i < 3; i++) cnt += time[p][i] < 0;
return cnt;
}
int solve() {
memset(dp, 0, sizeof dp);
int myScore = 0;
for (int i = 0; i < 3; i++) myScore += 100 * willHack[i] + submissionScore(score[i], time[0][i]);
ci = 0;
li = 1;
for (int p = 1; p < n; p++)
if (countHacks(p) > 0 && calcScore(p) > myScore) {
ci ^= 1;
li ^= 1;
for (int i = 0; i <= willHack[0]; i++)
for (int j = 0; j <= willHack[1]; j++)
for (int k = 0; k <= willHack[2]; k++)
dp[ci][i][j][k] = dp[li][i][j][k];
for (int ii = 0; ii < 2; ii++)
for (int jj = 0; jj < 2; jj++)
for (int kk = 0; kk < 2; kk++) {
if (ii == 1 && time[p][0] >= 0) continue;
if (jj == 1 && time[p][1] >= 0) continue;
if (kk == 1 && time[p][2] >= 0) continue;
int s = submissionScore(score[0], time[p][0]) * (ii ^ 1)
+ submissionScore(score[1], time[p][1]) * (jj ^ 1)
+ submissionScore(score[2], time[p][2]) * (kk ^ 1);
if (s > myScore) continue;
for (int i = ii; i <= willHack[0]; i++)
for (int j = jj; j <= willHack[1]; j++)
for (int k = kk; k <= willHack[2]; k++)
dp[ci][i][j][k] = max(dp[ci][i][j][k], dp[li][i - ii][j - jj][k - kk] + 1);
}
}
int res = 1 - dp[ci][willHack[0]][willHack[1]][willHack[2]];
for (int p = 1; p < n; p++) if (calcScore(p) > myScore) res++;
return res;
}
void brute(int p) {
if (p == 3) {
int res = solve();
bestPlace = min(bestPlace, res);
return;
}
for (int i = 0; i < 6; i++) {
int mn = i == 5 ? 0 : (n >> (i + 1)) + 1;
int mx = (n >> i);
if (solved[p] >= mn && solved[p] - canHack[p] <= mx) {
score[p] = 500 * (i + 1);
willHack[p] = min(canHack[p], solved[p] - mn);
brute(p + 1);
}
}
}
int main() {
memset(solved, 0, sizeof solved);
memset(canHack, 0, sizeof canHack);
scanf("%d", &n);
for (int i = 0; i < n; i++)
for (int j = 0; j < 3; j++) {
scanf("%d", &time[i][j]);
solved[j] += time[i][j] != 0;
canHack[j] += time[i][j] < 0;
}
if (canHack[0] + canHack[1] + canHack[2] > 89) {
printf("1\\n");
return 0;
}
bestPlace = n;
brute(0);
printf("%d\\n", bestPlace);
return 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 equal to $min = (1 \cdot pos - n \cdot neg)$, as each positive number can be $1$, but all negative can be $- n$. Similarly, the maximum possible value is equal to $max = (n \cdot pos - 1 \cdot neg)$. The solution therefore exists if and only if $min \le n \le max$. Now suppose a solution exists. Let's insert the numbers into the sum one by one from left to right. Suppose that we have determined the numbers for some prefix of the expression with the sum of $S$. Let the sign of the current unknown be $sgn$ ($+ 1$ or $- 1$) and there are some unknown numbers left to the right, excluding the examined unknown, among them $pos_left$ positive and $neg_left$ negative elements. Suppose that the current unknown number takes value $x$. How do we find out whether this leads to a solution? The answer is: in the same way we checked it in the beginning of the solution. Examine the smallest and the largest values of the total sum that we can get. These are equal to $min_left = (S + sgn \cdot x + pos_left - n \cdot neg_left)$ and $max_left = (S + sgn \cdot x + n \cdot pos_left - neg_left)$, respectively. Then we may set the current number to $x$, if $min_left \le n \le max_left$ holds. To find the value of $x$, we can solve a system of inequalities, but it is easier simply to check all possible values from $1$ to $n$.
|
[
"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;
}
scanf("%d", &n);
if (pos - n * neg > n || n * pos - neg < n) {
printf("Impossible\\n");
return 0;
}
printf("Possible\\n");
int S = 0;
for (int i = 0; i < k; i++) {
int sgn = 1;
if (i > 0 && s[i - 1] == '-') sgn = -1;
if (sgn == 1) pos--;
if (sgn == -1) neg--;
for (int x = 1; x <= n; x++)
if (S + x * sgn + pos - n * neg <= n && S + x * sgn + n * pos - neg >= n) {
printf("%d %c ", x, s[i]);
S += x * sgn;
break;
}
}
printf("%d = %d\\n", abs(n - m), n);
return 0;
}
|
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$, such that all integers $a, a + 1, a + 2, ..., b$ are divisible by $d$. To make the problem even more complicated we allow $a$ and $b$ to be up to googol, $10^{100}$ — such number do not fit even in 64-bit integer type!
|
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}$ minutes.
The driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish.
You know the time when Simion departed from the city $A$ to the city $B$. Calculate the number of buses Simion will meet to be sure in his counting.
|
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 intervals $(x = max(x_{1}, x_{2}), y = min(y_{1}, y_{2}))$ is not empty than Simion will count that bus. Complexity: $O(1)$.
|
[
"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 = max(x1, x2), y = min(y1, y2);
if (x < y)
ans++;
}
cout << ans << endl;
}
|
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 order.
Due to the space limitations all the items are arranged in one single row. When Ayush receives the $i$-th order he will find one by one all the items $a_{ij}$ ($1 ≤ j ≤ m$) in the row. Let $pos(x)$ denote the position of the item $x$ in the row at the moment of its collection. Then Ayush takes time equal to $pos(a_{i1}) + pos(a_{i2}) + ... + pos(a_{im})$ for the $i$-th customer.
When Ayush accesses the $x$-th element he keeps a new stock in the front of the row and takes away the $x$-th element. Thus the values are updating.
Your task is to calculate the total time it takes for Ayush to process all the orders.
You can assume that the market has endless stock.
|
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)
forn(j, m) {
int pos = int(find(p, p + k, a[i][j]) - p);
ans += pos + 1;
nfor(l, pos) p[l + 1] = p[l];
p[0] = a[i][j];
}
cout << ans << endl;
}
|
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 this task!
|
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 all the pairs of equal consecutive letters. On the other hand we can simply change the second, the fourth etc. symbols to letter that is not equal to the letters before and after the segment. The second approach: Let $z_{ka}$ be the minimal number of changes so that the prefix of length $k$ has no equal consecutive letters and the symbol $s'_{k}$ equals to $a$. Let's iterate over the letter on the position $k + 1$ and if it is not equal to $a$ make transition. The cost of the transition is equal to $0$ if we put the same letter as in the original string $s$ on the position $k + 1$. Otherwise the cost is equal to $1$. Complexity: $O(n)$.
|
[
"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 > INF / 2) continue;
forn(nj, A - 1) {
if (nj == j) continue;
int ct = nj != c;
if (z[i + 1][nj] > dv + ct) {
z[i + 1][nj] = dv + ct;
p[i + 1][nj] = j;
}
}
}
}
int idx = int(min_element(z[n], z[n] + A) - z[n]);
for (int i = n, j = idx; i > 0; j = p[i][j], i--)
ans[i - 1] = char('a' + j);
ans[n] = 0;
cerr << z[n][idx] << endl;
puts(ans);
}
|
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 array $a$ with the maximum size.
A prime number (or a prime) is a natural number greater than $1$ that has no positive divisors other than $1$ and itself.
Let's define a subset of the array $a$ as a tuple that can be obtained from $a$ by removing some (possibly all) elements of it.
|
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 to $1$, so their sum is also greater than $2$. So the subset $A$ is not simple. In this way $A$ consists of only two numbers greater than one (with a prime sum) or consists of some number of ones and also maybe other value $x$, so that $x + 1$ is a prime. We can simply process the first case in $O(n^{2})$ time. The second case can be processed in linear time. Also we should choose the best answer from that two. To check the value of order $2 \cdot 10^{6}$ for primality in $O(1)$ time we can use the simple or the linear Eratosthenes sieve. Complexity: $O(n^{2} + X)$, where $X$ is the maximal value in $a$.
|
[
"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] && i * p[j] < X; j++)
mind[i * p[j]] = p[j];
}
}
void printAns(int cnt1, int a = -1, int b = -1) {
vector<int> ans;
forn(i, cnt1) ans.pb(1);
if (a != -1) ans.pb(a);
if (b != -1) ans.pb(b);
assert(!ans.empty());
random_shuffle(all(ans));
cout << sz(ans) << endl;
forn(i, sz(ans)) {
if (i) putchar(' ');
printf("%d", ans[i]);
}
puts("");
}
void solve() {
int cnt1 = (int) count(a, a + n, 1);
function<bool(int)> isPrime = [](int p) { return mind[p] == p; };
if (cnt1 > 0)
forn(i, n)
if (a[i] != 1 && isPrime(a[i] + 1)) {
printAns(cnt1, a[i]);
return;
}
if (cnt1 > 1) {
printAns(cnt1);
return;
}
forn(i, n)
forn(j, i)
if (isPrime(a[i] + a[j])) {
printAns(0, a[i], a[j]);
return;
}
printAns(0, a[0]);
}
|
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 elements in the subarray is at least $k$.
Help ZS the Coder find the number of beautiful subarrays of $a$!
|
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 each iteration we should increase the answer by the value $z_{j}$ - the number of numbers $s_{i}$ ($i < j$) so $s_{j}\otimes s_{i}\geq k$. To do that we can use the trie data structure. Let's store in the trie all the values $s_{i}$ for $i < j$. Besides the structure of the trie we should also store in each vertex the number of leaves in the subtree of that vertex (it can be easily done during adding of each binary string). To calculate the value $z_{j}$ let's go down by the trie from the root. Let's accumulate the value $cur$ equals to the xor of the prefix of the value $s_{j}$ with the already passed in the trie path. Let the current bit in $s_{j}$ be equal to $b$ and $i$ be the depth of the current vertex in the trie. If the number $cur + 2^{i} \ge k$ then we can increase $z_{j}$ by the number of leaves in vertex $n t_{v,b\otimes1}$, because all the leaves in the subtree of tha vertex correspond to the values $s_{i}$ that for sure gives $s_{j}\otimes s_{i}\geq k$. After that we should go down in the subtree $b$. Otherwise if $cur + 2^{i} < k$ then we should simply go down to the subtree $b\otimes1$ and recalculate the value $cur = cur + 2^{i}$. Comlpexity by the time and the memory: $O(nlogX)$, where $X$ is the maximal xor on the prefixes.
|
[
"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) {
int v = 0;
cnt[v]++;
nfor(i, LOGN) {
int b = (x >> i) & 1;
if (nt[v][b] == -1) {
assert(tsz < V);
nt[v][b] = tsz++;
}
v = nt[v][b];
cnt[v]++;
}
}
int calc(int x) {
int v = 0;
int ans = 0;
auto getCnt = [](int v) { return v == -1 ? 0 : cnt[v]; };
int cur = 0;
nfor(i, LOGN) {
if (v == -1) break;
int b = (x >> i) & 1;
if ((cur | (1 << i)) >= k) {
ans += getCnt(nt[v][b ^ 1]);
v = nt[v][b];
} else {
v = nt[v][b ^ 1];
cur |= (1 << i);
}
}
if (cur >= k) ans += getCnt(v);
return ans;
}
void solve() {
clear();
add(0);
li ans = 0;
int s = 0;
forn(i, n) {
s ^= a[i];
li cur = calc(s);
ans += cur;
add(s);
}
cout << ans << endl;
}
|
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 $1$ and $10$ only the integers $6$, $8$ and $10$ has exactly four positive divisors. So, $D(10) = 3$.
You are given an integer $n$. You have to calculate $D(n)$.
|
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 number of primes from $1$ to $k$. Let's iterate over all the values $p$. Easy to see that $p\leq{\sqrt{n}}$. So for fixed $p$ we should increase the answer by the value $\pi(\lfloor{\frac{n}{p}}\rfloor)$. So the task is ot to find $\pi(\lfloor{\frac{n}{p}}\rfloor)$ - the number of primes not exceeding $\overset{n}{p}$, for all $p$. Denote $p_{j}$ the $j$-th prime number. Denote $dp_{n, j}$ the number of $k$ such that $1 \le k \le n$, and all prime divisors of $k$ are at least $p_{j}$ (note that 1 is counted in all $dp_{n, j}$, since the set of its prime divisors is empty). $dp_{n, j}$ satisfy a simple recurrence: $dp_{n, 1} = n$ (since $p_{1}$ = 2) $dp_{n, j} = dp_{n, j + 1} + dp_{ \lfloor n / pj \rfloor , j}$, hence $dp_{n, j + 1} = dp_{n, j} - dp_{ \lfloor n / pj \rfloor , j}$ Let $p_{k}$ be the smallest prime greater than $\sqrt{n}$. Then $ \pi (n) = dp_{n, k} + k - 1$ (by definition, the first summand accounts for all the primes not less than $k$). If we evaluate the recurrence $dp_{n, k}$ straightforwardly, all the reachable states will be of the form $dp_{ \lfloor n / i \rfloor , j}$. We can also note that if $p_{j}$ and $p_{k}$ are both greater than $\sqrt{n}$, then $dp_{n, j} + j = dp_{n, k} + k$. Thus, for each $ \lfloor n / i \rfloor $ it makes sense to keep only $\sim\pi({\sqrt{n/i}})$ values of $dp_{ \lfloor n / i \rfloor , j}$. Instead of evaluating all DP states straightforwardly, we perform a two-step process: Choose $K$. Run recursive evaluation of $dp_{n, k}$. If we want to compute a state with $n < K$, memorize the query ``count the numbers not exceeding $n$ with all prime divisors at least $k$''. Answer all the queries off-line: compute the sieve for numbers up to $K$, then sort all numbers by the smallest prime divisor. Now all queries can be answered using RSQ structure. Store all the answers globally. Run recurisive evaluation of $dp_{n, k}$ yet again. If we want to compute a state with $n < K$, then we must have preprocessed a query for this state, so take it from the global set of answers. The performance of this approach relies heavily on $Q$ - the number of queries we have to preprocess. Statement. $Q=O(\frac{n}{\sqrt{K_{\mathrm{\los}n}}})$. Proof: Each state we have to preprocess is obtained by following a $dp_{ \lfloor n / pj \rfloor , j}$ transition from some greater state. It follows that $Q$ doesn't exceed the total number of states for $n > K$. $Q\leq\sum_{j=1}^{n/K}\pi(\sqrt{n/j})\sim\Sigma_{j=1}^{n/K}\;\sqrt{n/j}/\log n\sim\textstyle{\frac{1}{\log n}}\int_{1}^{n/K}\;\sqrt{n/x}d x\sim\frac{n}{\sqrt{K\log n}}$ The preprocessing of $Q$ queries can be done in $O((K+Q)\log(K+Q))$, and it is the heaviest part of the computation. Choosing optimal $K\sim\left({\frac{n}{\log n}}\right)^{2/3}$, we obtain the complexity $O(n^{2/3}(\log n)^{1/3})$. Complexity: $O(n^{2/3}(\log n)^{1/3})$.
|
[
"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++] = i;
}
for (int j = 0; j < szp && j <= mind[i] && i * p[j] < N; j++)
mind[i * p[j]] = j;
}
}
inline int getk(li n) {
int lf = 0, rg = szp - 1;
while (lf != rg) {
int md = (lf + rg) >> 1;
if (p[md] * 1ll * p[md] > n) rg = md;
else lf = md + 1;
}
assert(p[lf] * 1ll * p[lf] > n);
return lf;
}
int t[K];
void inc(int i, int val) {
for ( ; i < K; i |= i + 1)
t[i] += val;
}
int sum(int i) {
int ans = 0;
for ( ; i >= 0; i = (i & (i + 1)) - 1)
ans += t[i];
return ans;
}
int szq;
pti q[Q];
int ans[Q];
vector<int> vs[P];
void process() {
sort(q, q + szq, greater<pti> ());
memset(t, 0, sizeof(t));
forn(i, szp) vs[i].clear();
fore(i, 2, K)
vs[mind[i]].pb(i);
inc(1, +1);
int p = szp - 1;
for (int i = 0, j = 0; i < szq; i = j) {
while (p >= q[i].x) {
for (auto v : vs[p])
inc(v, +1);
p--;
}
while (j < szq && q[j].x == q[i].x) {
ans[j] = sum(q[j].y);
j++;
}
}
}
map<pair<li, int>, li> z;
li solve(li n, int jj, bool fs) {
if (!n) return 0;
int j = min(jj, getk(n));
if (!j) return n + j - jj;
li ans = 0;
if (n < K) {
pti p(j, (int) n);
if (fs) {
assert(szq < Q);
q[szq++] = p;
ans = 0;
return 0;
} else {
int idx = int(lower_bound(q, q + szq, p, greater<pti> ()) - q);
assert(idx < szq && q[idx] == p);
ans = ::ans[idx];
}
} else {
if (!z.count(mp(n, j))) {
ans = solve(n, j - 1, fs);
ans -= solve(n / p[j - 1], j - 1, fs);
z[mp(n, j)] = ans;
} else {
ans = z[mp(n, j)];
}
}
ans += j - jj;
return ans;
}
inline li pi(li n, bool fs) {
int k = szp - 1;
return solve(n, k, fs) + k - 1;
}
void solve() {
szq = 0;
z.clear();
for (int j = 0; p[j] * 1ll * p[j] <= n; j++) {
li nn = n / p[j];
if (nn > p[j]) {
pi(n / p[j], true);
}
}
process();
z.clear();
li ans = 0;
for (int j = 0; p[j] * 1ll * p[j] <= n; j++) {
li nn = n / p[j];
if (nn > p[j]) {
ans += pi(n / p[j], false);
ans -= j + 1;
}
}
for (int i = 0; i < szp && p[i] * 1ll * p[i] * 1ll * p[i] <= n; i++)
ans++;
cout << ans << endl;
}
|
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 linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than $4$ letters. Then several strings with the length $2$ or $3$ symbols are appended to this word. The only restriction — it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word $s$. Find all distinct strings with the length $2$ or $3$, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word $abacabaca$ is given. This word can be obtained in the following ways: $\overline{{{d b|U(\bar{u})d\bar{u}/\partial l l e}}}\,\overline{{{\omega}}}_{\cdot}\,\overline{{{\omega}}}\overline{{{\omega}}}\overline{{{\omega}}}\overline{{{u}}}\overline{{{u}}}\overline{{{u}}}\prime{\cal O}\prime$, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is ${aca, ba, ca}$.
|
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_{2}[n]=d p_{3}[n-2]\vee\left(d p_{2}[n-2]\wedge s[n-3;n-2]\neq s[n-1;n]\right)$. Similarly, $d p_{3}[n]=d p_{2}[n-3]\lor(d p_{3}[n-3]\land s[n-5;n-3]\neq s[n-2;n])$. If any of $dp_{k}[n]$ is true we add the corresponding string to the set of answers.
|
[
"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 to his work and he wants to be distracted as little as possible. Therefore he will visit only four cities. These cities will be different, so no one could think that he has "favourites". Of course, to save money, he will chose the shortest paths between these cities. But as you have probably guessed, Cicasso is a weird person. Although he doesn't like to organize exhibitions, he likes to travel around the country and enjoy its scenery. So he wants the total distance which he will travel to be as large as possible. However, the sculptor is bad in planning, so he asks you for help.
There are $n$ cities and $m$ one-way roads in Berland. You have to choose four different cities, which Cicasso will visit and also determine the order in which he will visit them. So that the total distance he will travel, if he visits cities in your order, starting from the first city in your list, and ending in the last, choosing each time the shortest route between a pair of cities — will be the largest.
Note that intermediate routes may pass through the cities, which are assigned to the tour, as well as pass twice through the same city. For example, the tour can look like that: $\overline{{{\mathbf{I}}}}\cdot\ 2.\ 3.\ 4.\ \ \l4.\ \ \bar{\mathbf{f}}.\ 4.\ \ 3.\ \ \overline{{{\mathbf{2}}}}.\ \ \ 3.\ \ \overline{{{\mathbf{4}}}}$. Four cities in the order of visiting marked as overlines: $[1, 5, 2, 4]$.
Note that Berland is a high-tech country. So using nanotechnologies all roads were altered so that they have the same length. For the same reason moving using regular cars is not very popular in the country, and it can happen that there are such pairs of cities, one of which generally can not be reached by car from the other one. However, Cicasso is very conservative and cannot travel without the car. Choose cities so that the sculptor can make the tour using only the automobile. It is guaranteed that it is always possible to do.
|
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. Afterwards loop through each possible $b$ and $c$. Having them fixed, loop through $a$ among three most distant vertices from $b$ in the reversed graph and through $d$ among three most distant vertices from $c$ in tie initial graph. This is sufficient, because if we've fixed $b$ and $c$ and $d$ is not one of three furthest from $c$ then we could replace it with one of them and improve the answer.
|
[
"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. To open it one should solve the problem which is hard for others but is simple for you.
Every day the bunker generates a codeword $s$. Every time someone wants to enter the bunker, integer $n$ appears on the screen. As the answer one should enter another integer — the residue modulo $10^{9} + 7$ of the number of strings of length $n$ that consist only of lowercase English letters and contain the string $s$ as the \textbf{subsequence}.
The subsequence of string $a$ is a string $b$ that can be derived from the string $a$ by removing some symbols from it (maybe none or all of them). In particular any string is the subsequence of itself. For example, the string "cfo" is the subsequence of the string "codeforces".
You haven't implemented the algorithm that calculates the correct answers yet and you should do that ASAP.
|
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 otherwise the occurence is not lex-min. On the other hand, if there is an occurence which satsfies this criterion than it is lex-min. Given this definition we can count number of strings containing given string as a subsequence. At first select positions of the lex-min occurance; there are $\left(\begin{array}{l}{n k}\\ {|_{k\bar{\nu}}}\end{array}\right)$ ways to do it. Next, you can use any of $ \Sigma - 1$ characters at first $s$ intervals between $p_{i}$, and any of $ \Sigma $ at the end of the string. (Here, $ \Sigma $ denotes alphabet size). Looping through $p_{}|s|$ - the position of last character in $s$ in the lex-min occurence, we can count that there are exactly $\sum_{k=|s|}^{n}{\binom{k-1}{|s|-1}}(q-1)^{k-|s|}q^{n-k}=q^{n}\sum_{k=|s|}^{n}{\binom{k-1}{|s|-1}}{\frac{\left(q-1\right)^{k-|s|}}{q^{k}}}$ strings containing $s$ as a subsequence. So, having $|s|$ fixed, answer for each $n$ could be computed in linear time. A final detail: input strings can have at most $\sqrt{2n}$ different lengths. Thus simply applying the overmentioned formula we get a $O(n{\sqrt{n}})$ solution, which was the expected one.
|
[
"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. To open it one should solve the problem which is hard for others but is simple for you.
Every day the bunker generates a codeword $s$. Every time someone wants to enter the bunker, integer $n$ appears on the screen. As the answer one should enter another integer — the residue modulo $10^{9} + 7$ of the number of strings of length $n$ that consist only of lowercase English letters and contain the string $s$ as the \textbf{subsequence}.
The subsequence of string $a$ is a string $b$ that can be derived from the string $a$ by removing some symbols from it (maybe none or all of them). In particular any string is the subsequence of itself. For example, the string "cfo" is the subsequence of the string "codeforces".
You haven't implemented the algorithm that calculates the correct answers yet and you should do that ASAP.
|
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 will be constructed later. Then fix one of 24 permutations of initial points: first goes to the bottom-left point of the square, second goes to the bottom-right, etc. Having it fixed it is easy to check if this configuration is valid and relax the answer if needed. The only question is where to look for $d$, $x$ and $y$. First we deal with $d$. You can see that there are always two points which move among parallel but not the same lines. In this case $d$ is the distance between these lines, i.e. one of $|x_{i} - x_{j}|$ or $|y_{i} - y_{j}|$. This is the set from where $d$ will be chosen. Now fix $d$ from the overmentioned set and look at two cases. There are two points moving by perpendicular lines. Then there is a square vertex in the point of these lines intersection. In each coordinate this point either equals to bottom-left point of the square or differs by exactly $d$. Thus if bottom-left point has coordinates $(x_{0}, y_{0})$, than $x_{0}$ must be some of $x_{i}, x_{i} + d, x_{i} - d$, similarly for $y_{0}$. Add all this values to the set. All points are moving among parallel lines; WLOG horisontal. Let's fix a permutation of points (yes, once again) and shift each point in such a way that after moving it would equal the bottom-left vertex of the square. Second point should be shifted by $( - d, 0)$, third by $(0, - d)$, fourth by $( - d, - d)$. All four points must be on the same line now; otherwise this case is not possible with this permutation. Now the problem is: given four points on a line, move it to the same point minimizing the maximal path. Clearly, one should move points to the position $(maxX - minX) / 2$; rounding is irrelevant because of the constraint of integer answer. So, having looked through each permutations, we have another set for bottom-left vertex possible coordinates. By the way, the 10th test (and the first test after pretests) was case 2; it was intentionally not included in pretests. Why does it work fast? Let $D$ and $X$ be the sizes of corresponding lookup sets. $D=\left(_{4}^{2}\right)\cdot2=12$. Now for each $d$ there are $4 \cdot 3 = 12$ coordinates in the first case and no more than $4! = 24$ in the second. Thus $X \le 12 \cdot (12 + 24) = 432$. The main part works in $D\cdot X\cdot Y\cdot4!\sim5\cdot10^{5}$; however, it is impossible to build a test where all permutations in the second case give a valid position, so you can reduce this number. Actually, the model solution solves 50 testcases in 10ms without any kind of pruning.
|
[
"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.
Berland legal system uses the difficult algorithm in order to determine the guilt of the spy. The main part of this algorithm is the following procedure.
All the $m$ leaflets that are brought by the spy are numbered from $1$ to $m$. After that it's needed to get the answer to $q$ queries of the following kind: "{In which leaflet in the segment of numbers $[l, r]$ the substring of the Absolutely Inadmissible Swearword $[p_{l}, p_{r}]$ occurs more often?}".
The expert wants you to automate that procedure because this time texts of leaflets are too long. Help him!
|
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 from corresponding segment with delimeters like a#b. Also for each state in this automaton we should found the number of text in which this state state occurs most over all texts from the segment. Also for each state v in this automaton we should find such states in children of current segment tree vertex that include the set of string from v. If you maintain only such states that do not contain strings like a#b, it is obvious that either wanted state exists or there is no occurrences of strings from v in the texts from child's segment at all. Thus, to answer the query, firstly we find in root vertex the state containing string $s[a;b]$, and after this we go down the segment tree keeping the correct state via links calculated from the previous state. Please refer to the code if something is unclear.
|
[
"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 clear()\n\t{\n\t\tup.clear();\n\t\tto.clear();\n\t\tlen.clear();\n\t\tlink.clear();\n\t\tfpos.clear();\n\t\tlpos.clear();\n\t\tcnt.clear();\n\t\tst.clear();\n\t\ts.clear();\n\t}\n\t\n\tvoid reserve(int n)\n\t{\n\t\tup.reserve(n);\n\t\tto.reserve(n);\n\t\tlen.reserve(n);\n\t\tlink.reserve(n);\n\t\tfpos.reserve(n);\n\t\tlpos.reserve(n);\n\t\tcnt.reserve(n);\n\t\tst.reserve(n);\n\t\ts.reserve(n);\n\t\tleft.reserve(n);\n\t\tright.reserve(n);\n\t\tans.reserve(n);\n\t\tmax.reserve(n);\n\t}\n\t\n\tint make_state(vector<int> new_to = vector<int>(sigma + 1), int new_link = 0, int new_fpos = 0, int new_len = 0)\n\t{\n\t\tto.push_back(new_to);\n\t\tlink.push_back(new_link);\n\t\tfpos.push_back(new_fpos);\n\t\tlen.push_back(new_len);\n\t\tlpos.push_back(new_fpos);\n\t\tleft.push_back(0);\n\t\tright.push_back(0);\n\t\tans.push_back(0);\n\t\tmax.push_back(0);\n\t\tcnt.push_back(0);\n\t\tup.push_back(vector<int>(logn));\n\t\treturn sz++;\n\t}\n\t\n\tvoid add_letter(char c)\n\t{\n\t\ts += c;\n\t\tint p = last;\n\t\tlast = make_state(vector<int>(sigma + 1), 0, len[p] + 1, len[p] + 1);\n\t\tst.push_back(last);\n\t\tcnt[last] = 1;\n\t\tfor(; to[p][c] == 0; p = link[p])\n\t\t\tto[p][c] = last;\n\t\tif(to[p][c] == last)\n\t\t\treturn;\n\t\tint q = to[p][c];\n\t\tif(len[q] == len[p] + 1)\n\t\t{\n\t\t\tlink[last] = q;\n\t\t\treturn;\n\t\t}\n\t\tint cl = make_state(to[q], link[q], fpos[q], len[p] + 1);\n\t\tlink[last] = link[q] = cl;\n\t\tfor(; to[p][c] == q; p = link[p])\n\t\t\tto[p][c] = cl;\n\t}\n\t\n\tvoid build(string s)\n\t{\n\t\tmake_state();\n\t\tint n = s.size();\n\t\treserve(4 * n);\n\t\t\n\t\tfor(auto c: s)\n\t\t\tadd_letter(c);\n\t\t\n\t\tint mx_len[n]; // kill states like \"X#Y\"\n\t\tmemset(mx_len, 0, sizeof(mx_len));\n\t\tint count = 0;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tmx_len[i] = count++;\n\t\t\tif(s[i] == sigma)\n\t\t\t\tcount = 1;\n\t\t}\n\t\tfor(int state = 1; state < sz; state++) \n\t\t{\n\t\t\tif(len[link[state]] < mx_len[fpos[state] - 1] && len[state] > mx_len[fpos[state] - 1])\n\t\t\t{\n\t\t\t\tint cl = make_state(to[state], link[state], fpos[state], mx_len[fpos[state] - 1]);\n\t\t\t\tlink[state] = cl;\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tfor(int state = 1; state < sz; state++) // sparse table, like in LCA\n\t\t\tup[state][0] = link[state];\n\t\tfor(int lvl = 1; lvl < logn; lvl++)\n\t\t\tfor(int state = 1; state < sz; state++)\n\t\t\t\tup[state][lvl] = up[up[state][lvl - 1]][lvl - 1];\n\t\t\n\t\tvector<int> g[n + 1]; // this actually gives us reversed topsort\n\t\tfor(int state = 1; state < sz; state++)\n\t\t\tg[len[state]].push_back(state);\n\t\tfor(int ln = n; ln > 0; ln--) \n\t\t\tfor(auto state: g[ln])\n\t\t\t{\n\t\t\t\tif(link[state])\n\t\t\t\t\tcnt[link[state]] += cnt[state];\n\t\t\t\tlpos[link[state]] = std::max(lpos[link[state]], lpos[state]);\n\t\t\t}\n\t}\n\t\n\tint get(int pos, int ln) // kind of binary search on path to the root\n\t{ // pos 1-based\n\t\tint state = st[pos - 1];\n\t\tfor(int i = logn - 1; i >= 0; i--)\n\t\t\tif(len[up[state][i]] >= ln)\n\t\t\t\tstate = up[state][i];\n\t\treturn state;\n\t}\n} me[4 * maxn];\n\nvoid build(int v = 1, int l = 1, int r = maxn)\n{\n\tif(r - l == 1)\n\t{\n\t\ts[l] = char(sigma) + s[l];\n\t\tme[v].build(s[l]);\n\t\tfor(int state = 0; state < me[v].sz; state++)\n\t\t{\n\t\t\tme[v].ans[state] = l;\n\t\t\tme[v].max[state] = me[v].cnt[state];\n\t\t}\n\t\treturn;\n\t}\n\tint m = (l + r) / 2;\n\tbuild(2 * v, l, m);\n\tbuild(2 * v + 1, m, r);\n\tme[v].build(me[2 * v].s + me[2 * v + 1].s);\n\tfor(int state = 1; state < me[v].sz; state++)\n\t{\n\t\tif(me[v].fpos[state] <= (int) me[2 * v].s.size()) // we want to know states corresponding to strings from this state in children\n\t\t\tme[v].left[state] = me[2 * v].get(me[v].fpos[state], me[v].len[state]);\n\t\tif(me[v].lpos[state] > (int) me[2 * v].s.size())\n\t\t\tme[v].right[state] = me[2 * v + 1].get(me[v].lpos[state] - me[2 * v].s.size(), me[v].len[state]);\n\t\tme[v].max[state] = max(me[2 * v].max[me[v].left[state]], me[2 * v + 1].max[me[v].right[state]]);\n\t\tif(me[v].max[state] == me[2 * v].max[me[v].left[state]])\n\t\t\tme[v].ans[state] = me[2 * v].ans[me[v].left[state]];\n\t\telse\n\t\t\tme[v].ans[state] = me[2 * v + 1].ans[me[v].right[state]];\n\t}\n\tme[2 * v].clear(); // we don't need O(n log^2 n) memory\n\tme[2 * v + 1].clear();\n}\n\npair<int, int> get(int a, int b, int state, int v = 1, int l = 1, int r = maxn)\n{\n\tif(a <= l && r <= b)\n\t\treturn {me[v].max[state], me[v].ans[state]};\n\tif(r <= a || b <= l)\n\t\treturn {0, 0};\n\tint m = (l + r) / 2;\n\tauto A = get(a, b, me[v].left[state], 2 * v, l, m);\n\tauto B = get(a, b, me[v].right[state], 2 * v + 1, m, r);\n\tif(A.first >= B.first)\n\t\treturn A;\n\telse\n\t\treturn B;\n}\n\nint main()\n{\n ios::sync_with_stdio(0);\n cin.tie(0);\n string Q;\n cin >> Q;\n \n int n;\n cin >> n;\n for(int i = 0; i < n; i++)\n {\n\t\tcin >> s[i + 1];\n\t\tfor(auto &it: s[i + 1])\n\t\t\tit -= 'a';\n\t}\n\tbuild(); // yeah, this thing builds!\n\tint state = 0, ln = 0;\n\tvector<int> states, lens;\n\tfor(auto c: Q)\n\t{\n\t\tc -= 'a';\n\t\twhile(state && !me[1].to[state][c])\n\t\t{\n\t\t\tstate = me[1].link[state];\n\t\t\tln = me[1].len[state];\n\t\t}\n\t\tif(me[1].to[state][c])\n\t\t{\n\t\t\tstate = me[1].to[state][c];\n\t\t\tln++;\n\t\t}\n\t\tlens.push_back(ln);\n\t\tstates.push_back(state);\n\t}\n\t\n\tint m;\n\tcin >> m;\n\twhile(m--)\n\t{\n\t\tint l, r, pl, pr;\n\t\tcin >> l >> r >> pl >> pr;\n\t\tif(pr - pl + 1 > lens[pr - 1])\n\t\t{\n\t\t\tcout << l << ' ' << 0 << \"\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tint state = me[1].get(me[1].fpos[states[pr - 1]], pr - pl + 1);\n\t\tauto ans = get(l, r + 1, state);\n\t\tcout << max(l, ans.second) << ' ' << ans.first << \"\\n\";\n\t}\n return 0;\n}\n"
|
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 had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.
Thus, your cup is a cylinder with diameter equals $d$ centimeters. Initial level of water in cup equals $h$ centimeters from the bottom.
You drink a water with a speed equals $v$ milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on $e$ centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.
Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after $10^{4}$ seconds.
Note one milliliter equals to one cubic centimeter.
|
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 never do it.
|
[
"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-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.
Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The $i$-th rod is a segment of length $l_{i}$.
The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle $180^{\circ}$.
Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing.
Help sculptor!
|
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 sum of others. Assume it is greater by $k$; then it is sufficient to add a rod of length $k + 1$. More, it is clear that adding any shorter length wouldn't satisfy the inequality. Thus the answer for the problem is $\operatorname*{max}(l_{1},\cdot\cdot\cdot,l_{n})-(l_{1}+\cdot\cdot\cdot\cdot+l_{n}-\operatorname*{max}(l_{1},\cdot\cdot\cdot,l_{n}))+1$.
|
[
"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 Artem can't give her the same number of stones twice in a row. For example, he can give her $3$ stones, then $1$ stone, then again $3$ stones, but he can't give her $3$ stones and then again $3$ stones right after that.
How many times can Artem give presents to Masha?
|
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 if the first day of the year equals to the first day of the week (i.e. this day is Monday) in this year will be minimum possible number of the days off. If the first day of the year equals to the first day off of the week (i.e. this day is Saturday) in this year will be maximum possible number of the days off.
|
[
"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 identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the $n$-th robot says his identifier.
Your task is to determine the $k$-th identifier to be pronounced.
|
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 with robots identifiers and end our algorithm.
|
[
"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 decided to go to the cinema. There are $m$ movies in the cinema they came to. Each of the movies is characterized by two \textbf{distinct} numbers — the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different).
Scientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.
|
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} scientists. At first let $res = make_pair(0, 0)$. Now we need to iterate through all movies beginning from the first. Let the current movie has the number $i$. Then if $res < make_pair(cnt[b[i]], cnt[a[i]])$ let's make $res = make_pair(cnt[b[i]], cnt[c[i]])$ and update the answer with the number of current movie.
|
[
"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 morning, Apollinaria decided to bake cookies. To bake one cookie, she needs $n$ ingredients, and for each ingredient she knows the value $a_{i}$ — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all $n$ ingredients.
Apollinaria has $b_{i}$ gram of the $i$-th ingredient. Also she has $k$ grams of a magic powder. Each gram of magic powder can be turned to exactly $1$ gram of any of the $n$ ingredients and can be used for baking cookies.
Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.
|
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's make $b[i] = b[i] - a[i]$, else let's make $b[i] = 0$ and $val = val + a[i] - b[i]$. When we bruted all ingredients if $val > k$ than we can't bake more cookies. Else let's make $k = k - val$ and go to bake new cookie.
|
[
"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 morning, Apollinaria decided to bake cookies. To bake one cookie, she needs $n$ ingredients, and for each ingredient she knows the value $a_i$ — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all $n$ ingredients.
Apollinaria has $b_i$ gram of the $i$-th ingredient. Also she has $k$ grams of a magic powder. Each gram of magic powder can be turned to exactly $1$ gram of any of the $n$ ingredients and can be used for baking cookies.
Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.
|
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 ingredient has the number $i$. Then if $a[i] \cdot cur > b[i]$ let's make $cnt = cnt + a[i] \cdot cur - b[i]$. If after looking on some ingredient $cnt$ becomes more than $k$ the objective function must return $false$. If there is no such an ingredient the objective function must return $true$. If the objective function returned $true$ we need to move the left end of the binary search to the $cur$, else we need to move the right end of the binary search to the $cur$.
|
[
"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, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
- 1st bracket is paired with 8th,
- 2d bracket is paired with 3d,
- 3d bracket is paired with 2d,
- 4th bracket is paired with 7th,
- 5th bracket is paired with 6th,
- 6th bracket is paired with 5th,
- 7th bracket is paired with 4th,
- 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
- «L» — move the cursor one position to the left,
- «R» — move the cursor one position to the right,
- «D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
|
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 to the left bracket which did not delete and $right[i]$ will equals to the position of the closest to the right bracket which did not delete. If there are no such brackets we will store -1 in the appropriate position of the array. Let's the current position of the cursor equals to $p$. Then if the current operation equals to \texttt{L} let's make $p = left[p]$ and if the current operation equals to \texttt{R} let's make $p = right[p]$. We need now only to think how process the operation \texttt{D}. Let $lf$ equals to $p$ and $rg$ equals to $pos[p]$. If $lf > rg$ let's swap them. Now we know the ends of the substring which we need to delete now. If $right[rg] = = - 1$ we need to move $p$ to the left ($p = left[lf]$), else we need to move $p$ to the right ($p = right[rg]$). Now we need to recalculate the links for the ends of the deleted substring. Here we need to check is there any brackets which we did not deleted to the left and to the right from the ends of the deleted substring. To print the answer we need to find the position of the first bracket which we did not delete and go through all brackets which we did not delete (with help of the array $right$) and print all such brackets. To find the position of the first bracket which we did not delete we can store in the array all pairs of the ends of substrings which we deleted, then sort this array and find the needed position. Bonus: how we can find this position in the linear time?
|
[
"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 substring of $n$ (a substring of $n$ is a sequence of consecutive digits of the number $n$).
Vasya knows that there may be more than one way to restore the number $n$. Your task is to find the smallest possible initial integer $n$. Note that decimal representation of number $n$ contained no leading zeroes, except the case the integer $n$ was equal to zero itself (in this case a single digit 0 was used).
|
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 the given string all digits which appeared in the number $len$, generate three strings from the remaining digits and choose smaller string from them - this string will be the answer. Let $t$ is a substring which Vasya remembered. Which three strings do we need to generate? Let's write the string $t$ and after that let's write all remaining digits from the given string in the ascending order. This string can be build only if the string $t$ does not begin with the digit 0. Let's write at first the smallest digit from the remaining digits which does not equal to 0. If we have no such a digit we can't build such string. Else we need then to write all digits with smaller than the first digit in the $t$ in the ascending order, then write the string $t$ and then write all remaining digits in the ascending order. Let's write at first the smallest digit from the remaining digits which does not equal to 0. If we have no such a digit we can't build such string. Else we need then to write all digits with smaller than or equal to the first digit in the $t$ in the ascending order, then write the string $t$ and then write all remaining digits in the ascending order. Also we need to separately consider the case when the Vasya's number equals to zero.
|
[
"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 and Bera can carry only one bottle at once each.
For both Adil and Bera the process looks as follows:
- Choose to stop or to continue to collect bottles.
- If the choice was to continue then choose some bottle and walk towards it.
- Pick this bottle and walk to the recycling bin.
- Go to step $1$.
Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.
They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.
|
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}) - distance(Bin, Bottle_{i}) + distance(Bera, Bottle_{j}) - distance(Bin, Bottle_{j})$. Because for all bottles but the chosen ones we have to add $2$ $*$ $distance(bottle, bin)$. For example if we choose a bottle $i$ for Adil to take first then we have to add $distance(Adil, Bottle_{i})$ + $distance(Bottle_{i}, Bin)$. In defined $T$ we already count $2$ * $distance(Bottle_{i}, Bin)$ but we have to count $distance(Adil, Bottle_{i})$ + $distance(Bottle_{i}, Bin)$ for $i$. So we have to add $distance(Adil, Bottle_{i})$-$distance(Bottle_{i}, Bin)$ to $T$. Because $2$ * $distance(Bin, Bottle_{i})$+$distance(Adil, Bottle_{i})$-$distance(Bin, Bottle_{i})$ is equal to $distance(Adil, Bottle_{i})$+$distance(Bottle_{i}, Bin)$. Lets construct two arrays, $a_{i}$ will be $distance(Adil, Bottle_{i}) - distance(Bin, Bottle_{i})$, and $b_{j}$ will be $distance(Bera, Bottle_{j}) - distance(Bin, Bottle_{j})$. We will choose $i$ naively, after that we have to find minimum $b_{j}$ where $j$ is not equal to $i$. This one easily be calculated with precalculations, let's find optimal $opt1$ for Bera, also we will find second optimal $opt2$ for Bera, if our chosen $i$ is equal to $opt1$ then Bera will go $opt2$, otherwise he will go $opt1$. Don't forget to cases that all bottles taken by Adil or Bera!
|
[
"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;ii>=bb;ii--)\n#define mp make_pair\n#define nd second\n#define st first\n#define type(x) __typeof(x.begin())\n\ntypedef pair < int ,int > pii;\n\ntypedef long long ll;\n\nconst long long linf = 1e18+5;\nconst int mod = (int) 1e9 + 7;\nconst int logN = 17;\nconst int inf = 1e9;\nconst int N = 1e6 + 5;\n\nint Kx, Ky, Cx, Cy, Tx, Ty, n, x, y;\n\ndouble pre[N], suff[N], add[N], all;\n\ndouble dist(int x, int y, int a, int b) { return sqrt((ll) (x - a) * (x - a) + (ll) (y - b) * (y - b)); }\n\nint main() {\n\n\tscanf(\"%d %d %d %d %d %d\", &Kx, &Ky, &Cx, &Cy, &Tx, &Ty);\n\n\tscanf(\"%d\", &n);\n\n\tFOR(i, 1, n) {\n\t\tscanf(\"%d %d\", &x, &y);\n\t\tdouble add = dist(Tx, Ty, x, y);\n\t\tall += add * 2;\n\t\tsuff[i] = pre[i] = dist(Cx, Cy, x, y) - add;\n\t\t::add[i] = dist(Kx, Ky, x, y) - add;\n\t}\n\t\n\tpre[0] = suff[n+1] = linf;\n\tFOR(i, 1, n) { pre[i] = min(pre[i-1], pre[i]); }\n\tROF(i, n, 1) { suff[i] = min(suff[i+1], suff[i]); }\n\n\tdouble ans = suff[1] + all;\n\n\tFOR(i, 1, n) \n\t\tans = min(ans, all + min(0.0, min(pre[i-1], suff[i+1])) + add[i]);\n\n\tprintf(\"%.12lf\\n\", ans);\n\n\treturn 0;\n}\n"
|
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 give it to the poorest person (poorest person right after taking richest's $1$ coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in $k$ days. He decided to spend these last days with helping poor people.
After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.
Your task is to find the difference between richest and poorest persons wealth after $k$ days. Note that the choosing at random among richest and poorest doesn't affect the answer.
|
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 minimum value after applying k operation. Let's look how to check if minimum will be great or equal to $p$. If $\sum_{p=1}^{n}m a x(0,\,p-c_{i})$ is less or equal to $k$ then we can increase all elements to at least $p$. In this way we can find what will be minimum value after $k$ operations. Let's say this minimum value to $m$. After we find it we will increase all numbers less than $m$ to $m$. But there may be some operations we still didn't apply yet, this number can be at most $n - 1$, otherwise minimum would be greater than $m$ because we can increase all numbers equal to $m$ by one with this number of increases. Since minimum has to be same we just have to increase some elements in our array that equal to $m$. We will use same algorithm for decreasing operations. Finally we will print $max element$ - $min element$ in final array. Overall complexity will be $O(nlogk)$.
|
[
"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 bit(x,y) ((x>>y)&1)\n\nll t;\nint a[N],i,j,k,n,m,x,y,z;\n\nint main(){\n\tcin >> n >> k;\n\n\tfor(i=1 ; i<=n ; i++)\n\t\tscanf(\"%d\",a+i);\n\t\n\tint bas=1;, son=2*inf;\n\t\n\twhile(bas<son){\n\t\tint ort = ((ll)bas+son)/2;\n\t\tif(bas==ort)\n\t\t\tort++;\n\t\tt = 0;\n\t\tfor(i=1 ; i<=n ; i++)\n\t\t\tt += max(0 , ort-a[i]);\n\t\tif(t <= k)\n\t\t\tbas = ort;\n\t\telse\n\t\t\tson = ort-1;\n\t}\n\t\n\tt = k;\n\t\n\tfor(i=1 ; i<=n ; i++){\n\t\tt -= max(0 , bas-a[i]);\n\t\ta[i] = max(a[i] , bas);\n\t}\n\t\n\tfor(i=1 ; i<=n ; i++)\n\t\tif(a[i] == bas and t){\n\t\t\tt--;\n\t\t\ta[i]++;\n\t\t}\n\t\n\tbas=1, son=2*inf;\n\t\n\twhile(bas<son){\n\t\tint ort = ((ll)bas+son)/2;\n\t\tt = 0;\n\t\tfor(i=1 ; i<=n ; i++)\n\t\t\tt += max(0 , a[i]-ort);\n\t\tif(t <= k)\n\t\t\tson = ort;\n\t\telse\n\t\t\tbas = ort+1;\n\t}\n\t\n\tt = k;\n\t\n\tfor(i=1 ; i<=n ; i++){\n\t\tt -= max(0 , a[i]-bas);\n\t\ta[i] = min(a[i] , bas);\n\t}\n\t\n\tfor(i=1 ; i<=n ; i++)\n\t\tif(a[i] == bas and t){\n\t\t\tt--;\n\t\t\ta[i]--;\n\t\t}\n\n\tcout << *max_element(a+1,a+1+n) - *min_element(a+1,a+1+n) << endl;\n\n}\n"
|
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 also defines the ultimate weirdness of an array. Ultimate weirdness is $\sum_{i=1}^{n}\sum_{j=i}^{n}f(i,\,j)$ where $f(i, j)$ is weirdness of the new array $a$ obtained by removing all elements between $i$ and $j$ inclusive, so new array is $[a_{1}... a_{i - 1}, a_{j + 1}... a_{n}]$.
Since 5 year old boys can't code, Yasin asks for your help to find the value of ultimate weirdness of the given array $a$!
|
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 $1$. When we are iterating we will keep another array $next$, Let's suppose we are iterating over $i$, $next_{j}$ will keep leftmost $k$ where $f(j, k)$ $ \le $ $i$. Sometimes there is no such $k$, then $next_{j}$ will be $n + 1$. $H_{i}$ will be equal to $\sum_{p=1}^{n}n-n e x t_{p}+1$, because if we choose p as $l$, $r$ must be at least $next_{p}$, so for $l$ we can choose $n$-$next_{p}$+$1$ different $r$ s. Let's look how we update $next$ array when we iterate $i$ to $i - 1$. Let $v_{i}$ be $b_{1}, b_{2}, b_{3}...b_{k}$. Note that our $l - r$ must be cover at least $k - 1$ of this indexes. $l$ must less or equal to $b_{2}$. So we have to maximize all $next_{p}$ with $n + 1$ where $p > b_{2}$. Otherwise If $l \ge b_{1} + 1$ then $r$ must be at least $b_{k}$, that's we will maximize all $next_{p}$'s where $b_{1} < p \le b2$ with $b_{k}$. And finally for all $next_{p}$'s where $(1 \le p \le b_{1})$ we have to maximize them with $b_{k - 1}$. Observe that $next$ array will be monotonic $-$ in non decreasing order $-$ after all operations. So we can easily make our updates with a segment tree that can perform following operations: $-$Returns rightmost index $i$ where $next_{i}$ is less than some $k$. $-$Returns sum of all elements in $next$ array. $-$Can assign some $k$ to all elements between some $l$ and $r$. If all update and queries performed in $O(logn)$ then overall complexity will be $O(nlogn)$, we can also apply all this operations with STL set in same complexity.
|
[
"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>=bb;ii--)\n\n#define type(x) __typeof(x.begin())\n\n#define orta (bas + son >> 1)\n#define sag (k + k + 1)\n#define sol (k + k)\n\n#define pb push_back\n#define mp make_pair\n\n#define nd second\n#define st first\n\n#define endl '\\n'\n\ntypedef pair < int ,int > pii;\n\ntypedef long long ll;\n\nconst long long linf = 1e18+5;\nint mod = (int) 1e9 + 7;\nconst int logN = 18;\nconst int inf = 1e9;\nconst int N = 2e5 + 5;\n\nint n, m, x, y, z, a[N];\nvector< int > H[N], v[N];\nll sum = 0, ans[N];\n\nset< pair< pii , int > > S;\n\nvoid divide(int x) {\n set< pair< pii , int > > :: iterator it, it2;\n it = S.lower_bound(mp(mp(x + 1, 0), -1));\n if(it == S.begin()) return ; it--;\n if(it->st.nd < x) return ;\n pair< pii , int > t = *it; S.erase(*it);\n S.insert(mp(mp(t.st.st, x), t.nd));\n if(x + 1 <= t.st.nd) S.insert(mp(mp(x + 1, t.st.nd), t.nd));\n}\n\nvoid remove(int x) {\n divide(x - 1);\n while(S.rbegin()->st.st >= x) {\n pair< pii , int > t = *S.rbegin();\n sum -= (t.st.nd - t.st.st + 1) * (ll) (t.nd);\n S.erase(S.find(t));\n }\n}\n\nvoid maximize(set< pair< pii , int > > :: iterator it, int x, int y) {\n pair< pii , int > t; t.nd = x; t.st.st = y;\n set< pair< pii , int > > :: iterator it2;\n while(it != S.end()) {\n if(it->nd >= x) break;\n t.st.nd = it->st.nd;\n sum -= (it->st.nd - it->st.st + 1) * (ll) (it->nd);\n it2 = it; it2++; S.erase(it); it = it2;\n }\n if(t.st.st <= t.st.nd) {\n sum += (t.st.nd - t.st.st + 1) * (ll) t.nd;\n S.insert(t);\n }\n}\n\nint main() {\n\n scanf(\"%d\", &n);\n\n FOR(i, 1, n) {\n scanf(\"%d\", &a[i]);\n H[a[i]].pb(i); sum += i;\n S.insert(mp(mp(i, i), i));\n }\n\n FOR(i, 1, N - 1)\n for(int j = i; j < N; j += i)\n foreach(it, H[j])\n v[i].pb(*it);\n\n ans[N - 1] = n * (ll) (n + 1) / 2;\n\n ROF(i, N - 2, 1) {\n int l = v[i].size() - 1;\n if(l <= 0) { ans[i] = ans[i + 1]; continue; }\n sort(v[i].begin(), v[i].end()); remove(v[i][1] + 1);\n maximize(S.begin(), v[i][l-1], 1);\n divide(v[i][0]); maximize(S.lower_bound(mp(mp(v[i][0] + 1, v[i][0]), 0)), v[i][l], v[i][0] + 1);\n ans[i] = (S.rbegin()->st.nd * (ll)(n + 1) - sum);\n }\n\n ll all = 0;\n\n FOR(i, 1, N - 2) all += (ans[i + 1] - ans[i]) * (ll) i;\n\n printf(\"%lld\\n\", all);\n\n return 0;\n}\n"
|
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 only one road repairing company in town, named "RC company". Company's center is located at the intersection $1$. RC company doesn't repair roads you tell them. Instead, they have workers at some intersections, who can repair only some specific paths. The $i$-th worker can be paid $c_{i}$ coins and then he repairs \textbf{all roads} on a path from $u_{i}$ to some $v_{i}$ that \textbf{lies on the path} from $u_{i}$ to intersection $1$.
Mayor asks you to choose the cheapest way to hire some subset of workers in order to repair all the roads in Yusland. It's allowed that some roads will be repaired more than once.
If it's impossible to repair all roads print $ - 1$.
|
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$ is in the path between $u_{i}$ and $v_{i}$ with cost $c_{i}$, also paths must not intersect. In this way we will never find better solution from original problem and we can express optimal subset in original problem without any path intersections in new problem. Let's keep a $dp$ array, $dp_{i}$ keeps minimum cost to cover all edges in subtree of node $i$, also the edge between $i$ and $parent_{i}$. How to find answer of some $i$. Let's choose a worker which $u_{j}$ is in the subtree of $i$ and $v_{j}$ is a parent of node $i$. Then if we choose this worker answer must be $c_{j}$ + ($dp_{k}$ where $k$ is child of a node in the path from $u_{j}$ to $i$ for all $k$'s). Of course we have to exclude nodes chosen as $k$ and in the path from $u_{j}$ to $i$ since we will cover them with $j$-th worker. We will construct a segment tree by dfs travel times so that for all nodes, workers which start his path in subtree of this node can be reached by looking a contiguous segment in tree. In node $i$, segment will keep values what will be $dp_{i}$ equal to if we choose this worker to cover path between $u_{j}$ and $parent_{i}$. We will travel our tree with dfs, in each $i$ after we calculated node $i$'s children dp's we will update our segment in following way, add all workers to segment where $u_{j} = i$ with value $c_{j}$ + (sum of node $i$'s children dp's). For all workers $v_{j}$ equal to $i$, we must delete it from segment, this is assigning $inf$ to it. The only thing we didn't handle is what to do with workers under this node. Imagine all updates in subtree of node $k$ where $k$ is a child of node $i$. We have to increase all of them by (sum of node $i$'s children dp's-$dp_{k}$). After applying all of this operations answer will be minimum value of workers start their path from a node in subtree of $i$ in segment tree. Overall complexity will be $((n + m)logm)$. Please look at the code to be more clear.
|
[
"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;ii>=bb;ii--)\n#define mp make_pair\n#define nd second\n#define st first\n#define type(x) __typeof(x.begin())\n\ntypedef pair < int ,int > pii;\n\ntypedef long long ll;\n\nconst long long linf = 1e15+5;\nconst int mod = (int) 1e9 + 7;\nconst int logN = 17;\nconst int inf = 1e9;\nconst int N = 1e6 + 5;\n\nint n, m, x, y, z, c[N], start[N], finish[N], w[N], T;\nvector< int > v[N], add[N], del[N];\nll dp[N], ST[N << 2], L[N << 2]; \n\nvoid dfs(int node, int root) {\n\tstart[node] = T + 1;\n\tforeach(it, add[node]) w[*it] = ++T;\n\tforeach(it, v[node]) {\n\t\tif(*it != root) {\n\t\t\tdfs(*it, node);\n\t\t}\n\t} finish[node] = T;\n}\n\nll update(int k, int bas, int son, int x, ll D) {\n\tif(bas > x || son < x) return ST[k];\n\tif(bas == son) return ST[k] = D;\n\tST[k] = min(update(sol, bas, orta, x, D), update(sag, orta + 1, son, x, D)) + L[k];\n if(ST[k] > linf) ST[k] = linf;\n\treturn ST[k];\n\n}\n\nll update(int k, int bas, int son, int x, int y, ll D) {\n\tif(bas > y || son < x) return ST[k];\n\tif(x <= bas && son <= y) {\n\t\tL[k] = min(linf, D + L[k]);\n\t\tST[k] = min(linf, D + ST[k]);\n\t\treturn ST[k];\n\t}\n\tST[k] = min(update(sol, bas, orta, x, y, D), update(sag, orta + 1, son, x, y, D)) + L[k];\n\tif(ST[k] > linf) ST[k] = linf;\n\treturn ST[k];\n}\n\nll query(int k, int bas, int son, int x, int y) {\n\tif(bas > y || son < x) return linf;\n\tif(x <= bas && son <= y) return ST[k];\n\treturn min(linf, min(query(sol, bas, orta, x, y), query(sag, orta + 1, son, x, y)) + L[k]);\n}\n\nll solve(int node, int root) {\n\tll all = 0;\n\tforeach(it, v[node]) {\n\t\tif(*it == root) continue;\n\t\tall += solve(*it, node);\n\t\tif(all != 2 * linf)\n\t\t all = min(all, 2 * linf);\n\t}\n\tif(node == 1) return dp[node] = all;\n\tforeach(it, add[node]) update(1, 1, m, w[*it], c[*it] + all);\t\n\tforeach(it, del[node]) update(1, 1, m, w[*it], linf);\t\n\tforeach(it, v[node])\n\t\tif(*it != root)\n\t\t\tupdate(1, 1, m, start[*it], finish[*it], all - dp[*it]);\n\tdp[node] = query(1, 1, m, start[node], finish[node]);\n\treturn dp[node];\n}\n\nint main() {\n\n\tscanf(\"%d %d\", &n, &m);\n\n\tFOR(i, 2, n) {\n\t\tscanf(\"%d %d\", &x, &y);\n\t\tv[x].pb(y); v[y].pb(x);\n\t}\n\n\tFOR(i, 1, m) {\n\t\tscanf(\"%d %d %d\", &x, &y, &c[i]);\n\t\tadd[x].pb(i);\n\t\tdel[y].pb(i);\n\t}\n\t\n\tdfs(1, 0);\n\n\tll ans = solve(1, 0);\n\n\tif(ans >= linf) ans = -1;\n\n\tprintf(\"%lld\\n\", ans);\n\n\treturn 0;\n}\n"
|
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. There is no other way to get gas in Kekoland.
You were hired by the Kekoland president Keko to organize the most beautiful race Kekoland has ever seen. Let race be between cities $l$ and $r$ ($l ≤ r$). Race will consist of two stages. On the first stage cars will go from city $l$ to city $r$. After completing first stage, next day second stage will be held, now racers will go from $r$ to $l$ with their cars. Of course, as it is a race, racers drive directly from start city to finish city. It means that at the first stage they will go only right, and at the second stage they go only left. Beauty of the race between $l$ and $r$ is equal to $r - l + 1$ since racers will see $r - l + 1$ beautiful cities of Kekoland. Cars have infinite tank so racers will take all the gas given to them.
At the beginning of \textbf{each stage} racers start the race with empty tank ($0$ liters of gasoline). They will immediately take their gasoline in start cities ($l$ for the first stage and $r$ for the second stage) right after the race starts.
It may not be possible to organize a race between $l$ and $r$ if cars will run out of gas before they reach finish.
You have $k$ presents. Each time you give a present to city $i$ its value $g_{i}$ increases by $1$. You may distribute presents among cities in any way (also give many presents to one city, each time increasing $g_{i}$ by $1$). What is the most beautiful race you can organize?
Each car consumes $1$ liter of gas per one kilometer.
|
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) possible. Greedily we will make our increases in right as much as possible. So if we run out of gas in road between $i$ and $i$+$1$ we will add just enough gasoline to $G_{i}$. After make first stage possible we will add gasoline to $r$ just enough to make second stage possible. This solution will be $O(n^{3})$. Let's find $next_{i}$, $next_{i}$ will keep leftmost $j$ that we can't reach with current gasoline, we will also keep $need_{i}$ that keeps how many liter gasoline we have to add to $next_{i}$-1. After applying this increase city $next_{i}$ will be reachable from $i$, cars will be consumed all of their gasoline just before taking gasoline in city $next_{i}$. How to find it: We will keep an array $pre$ where $pre_{i}$ $=$ $pre_{i - 1}$ + $G_{i}$-$W_{i}$. If $pre_{j}$-$pre_{i - 1}$ < 0 then we can't reach to $j$ + $1$. If we find leftmost $j$ ($j \ge i$) where $pre_{j}$ is strictly smaller than $pre_{i}$ then $next_{i}$ will be equal to $j$ and $need_{i}$ will be equal to $pre_{j}$-$pre_{i - 1}$. Building tree: Let's make a tree where $next_{i}$ is father of node $i$. In dfs travel, when we are in a node $i$ all increases will be made to make all first stages possible from $i$ to all $j$'s, now we will keep an array $suff$ where $suff_{i}$ $=$ $suff_{i - 1}$ + $G_{i}$-$W_{i - 1}$. So when we are increasing a city $u$'s $G_{u}$ we have to increase all $suff$ values from u to $n$. We will also keep another array $cost$, $cost_{j}$ will keep the cost to make stage 1 possible from $i$ to $j$+$1$. Increases will be nearly same, for $u$ we will increase all $v$'s costs $v \ge u$. So when we reach a node $i$ we will apply increases to make first stage possible between $i$ ans $next_{i}$. When we are done with this node, we will revert increases. Last part: Now we have to find rightmost $j$ for all $i$'s. Let's look at whether it is possible or not for a j. We can check it in $O(1)$. First $cost_{j - 1}$ must be less or equal to $k$, also $maximum(suff_{k} i \le k < j)$-($suff_{j}$-$delta_{j}$) + ($cost_{j}$-$delta_{j}$) $ \le $ $k$. $delta_{j}$ keeps how many increases we apply to node $j$. We will decrease them since direct increases in $j$ are made for $j$+$1$, we don't need to keep $delta$ array since it will not effect expression. Also observe that the only thing changes in expression is $maximum(suff_{k} i \le k < j)$. In this way problem can be solved in $O(n^{2})$. Both sqrt dec. solutions are using the same idea. Main solution will be posted soon. Let $p_{i}$ be $cost_{i}$-$suff_{i}$. As we said before this value will never change. Let's keep a segment tree. In each node we will keep such values. Assume this node of segment covers between $l$ and $r$. We will keep such $ind1$, $ind2$ and $mx_{suff}$. $ind1$ will keep minimum $p_{j}$'s index where $l \le j \le r$. $ind2$ will keep minimum ($maximum{suff_{l \le k < j}}$+$p_{j}$)'s index where $mid + 1 \le j \le r$ this means we have to choose $j$ from this nodes right child. $mx_{suff}$ will keep $maximum{suff_{l \le k \le r}}$. We also have to keep values for $ind1$ and $ind2$ ($p_{ind1}$ and ($maximum{suff_{l \le k < ind2}}$+$p_{ind2}$)). How to update them: In a update we will increase some some suffixes $cost_{i}$ and $suff_{i}$ values. So $ind1$ will be same for each node. For every covered node $mx_{suff}$ will increase by $k$ ($k$ is increase value in update). Tricky part is how to update $ind2$. Let's define a function $relax()$. $relax(u)$ calculates $ind2$ value for node $u$. Note that for relax function to work all nodes in subtree of $u$ must be calculated already. We will call relax function after calculating this nodes children. We will come to relax function later. How to query: We can use pretty much same function as relax. We have to query find values for a $l$-$r$ segment. We will keep an extra value in function, let's call it $t$. If this node covers segment $a$-$b$ then $t$ will keep $maximum{suff_{l \le k < a}}}$. If this node doesn't intersect with $l$-$r$ segment we will return worst values (for example for mx_suff value we will return -inf). Let's look what to do when this node is covered by $l$-$r$. If $mx_{suff}$ value of this node's left child is greater or equal to $t$ then $ind2$ value will be same. So if $maximum{suff_{l \le k < ind2}}$+$p_{ind2}$) is lower or equal to $k$ for this node answer is ind2, it is greater than $k$ then we will go this nodes left child to calculate answer. If $mx_{suff}$ value of this node's left child is lower than $t$ value then ($maximum{suff_{l \le j < mid}}$) will equal to $t$ for each $j$. So we just have to rightmost $j$ that $p_{j}$ $ \le $ $k - t$ in subtree of this node. This can be calculated in $O(logn)$ time. We didn't look at right child yet, so we will go to right child again with same $t$ value. What to do when this node intersects with $l$-$r$ and $l$-$r$ doesn't cover it. We will go both children, first to left, after we will update $t$ value for right child by $mx_{suff}$ value returned from left child. We will lazy prop to push values. Other condition: In node $l$ we have to query between $l$ and $r$, $r$ is rightmost index that $cost_{r - 1}$ < $k$. Since cost values are monotonic this $r$ can be found easily in $O(logn)$. Relax function can be calculated nearly same as query. But this will work in $O(logn)$, since we just have to go exactly one child, since we don't interested in rightmost values.
|
[
"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];\nvector<int> E[N];\n\nint n, k;\n\nstruct block {\n int len = 0;\n llong X[K] = {0};\n llong dA[K] = {0}; // Subject to further optimization\n llong glob = 0;\n llong max_req = -(llong)1e18;\n llong max_X = -(llong)1e18;\n\n void add_global(llong d) {\n glob += d;\n }\n\n inline llong get_max_req() const {\n return max_req;\n }\n\n inline llong get_max_X() const {\n return max_X + glob;\n }\n \n void recalc() {\n assert(glob == 0);\n max_req = -(llong)1e18;\n for (int i = 0; i < len; i++) {\n llong got = i ? dA[i - 1] : 0;\n if (got > k)\n break;\n max_req = max(max_req, X[i] + k - got);\n }\n max_X = *max_element(X, X + len);\n }\n \n void flush() {\n for (int i = 0; i < len; i++) {\n X[i] += glob;\n dA[i] += glob;\n }\n max_X += glob;\n glob = 0;\n }\n\n void add_suff(int x, llong d) {\n flush();\n for (int i = x; i < len; i++) {\n X[i] += d;\n dA[i] += d;\n }\n recalc();\n }\n \n // ans, mx\n pair<int, llong> get(int l, llong prev_mx = -1e18) const {\n llong mx = prev_mx;\n if (l != -1)\n mx = X[l] + glob;\n int ans = 0;\n for (int i = l + 1; i < len; i++) {\n llong got_prev = (i ? dA[i - 1] : -(llong)1e18) + glob;\n llong got = dA[i] + glob;\n if (got_prev > k)\n break;\n if (X[i] + glob + k - got >= mx) {\n ans = max(ans, i - l);\n }\n mx = max(mx, X[i] + glob);\n }\n return make_pair(ans, mx);\n }\n} B[N / K + 2];\n\nint blocks;\n\nvoid add_suff(int l, llong d) {\n int id = l / K;\n B[id].add_suff(l - id * K, d);\n while (++id < blocks) {\n B[id].add_global(d);\n }\n}\n\nint ans = 1;\n\nvoid process(int l) {\n int ans;\n llong mx;\n int id = l / K;\n tie(ans, mx) = B[id].get(l - id * K);\n ++ans;\n int good_id = -1;\n llong good_mx = -42;\n int prev_good_id = -1;\n llong prev_good_mx = -42;\n while (++id < blocks) {\n if (B[id - 1].dA[K - 1] + B[id - 1].glob > k)\n break;\n if (B[id].get_max_req() >= mx) {\n prev_good_id = good_id;\n prev_good_mx = good_mx;\n good_id = id;\n good_mx = mx;\n }\n mx = max(mx, B[id].get_max_X());\n }\n if (good_id != -1) {\n if ((good_id + 1) * K - l <= ::ans)\n return;\n int ans2;\n tie(ans2, ignore) = B[good_id].get(-1, good_mx);\n if (ans2 == 0) {\n if (prev_good_id != -1) {\n if ((prev_good_id + 1) * K - l <= ::ans)\n return;\n tie(ans2, ignore) = B[prev_good_id].get(-1, prev_good_mx);\n assert(ans2 != -1);\n ans = ans2 + prev_good_id * K - l;\n }\n } else {\n ans = ans2 + good_id * K - l;\n }\n }\n //eprintf(\"l = %d -> ans = %d\\n\", l, ans);\n ::ans = max(::ans, ans);\n}\n\nvoid DFS(int x, int p = -1) {\n was[x] = true;\n if (p != -1)\n add_suff(p - 1, PS[x] - PS[p]);\n process(x);\n for (int y : E[x]) {\n DFS(y, x);\n }\n if (p != -1)\n add_suff(p - 1, PS[p] - PS[x]);\n}\n\nint main() {\n scanf(\"%d %d\", &n, &k);\n for (int i = 0; i < n - 1; i++) {\n scanf(\"%d\", &D[i]);\n }\n for (int i = 0; i < n; i++) {\n scanf(\"%d\", &A[i]);\n }\n for (int i = 1; i < n; i++) {\n PS[i] = PS[i - 1] + A[i - 1] - D[i - 1];\n }\n int pt = 0;\n for (int i = n - 1; i >= 0; i--) {\n while (pt > 0 && PS[st[pt - 1]] >= PS[i])\n --pt;\n if (pt)\n E[st[pt - 1]].push_back(i);\n st[pt++] = i;\n }\n llong curX = 0;\n for (int i = 1; i < n; i++)\n curX = B[i / K].X[i % K] = curX + A[i] - D[i - 1];\n blocks = (n + K - 1) / K;\n for (int id = 0; id < blocks; id++) {\n B[id].len = min(K, n - id * K);\n B[id].recalc();\n }\n for (int i = 0; i < n; i++) {\n reverse(E[i].begin(), E[i].end());\n }\n for (int i = n - 1; i >= 0; i--) {\n if (!was[i])\n DFS(i);\n }\n printf(\"%d\\n\", ans);\n}\n"
|
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 to print the $n$-th digit of this string (digits are numbered starting with $1$.
|
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 number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string $s$ has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
|
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$ elements must be stay as before, all others must be changed. So will be ($n$ - $k$).
|
[
"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 ort ((bas+son)>>1)\n#define bit(x,y) ((x>>y)&1)\n\nint main(){\n\tint H[500]={0};\n\tint t=0,i,n;\n\tchar str[N];\n\n\tcin >> n;\n\n\tscanf(\"%s\",str);\n\n\tfor(i=0 ; i<n ; i++)\n\t\tt += (H[str[i]]++) == 0;\n\n\tif(n > 26)\n\t\tputs(\"-1\");\n\telse\n\t\tcout << n - t << endl;\n}\n"
|
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}, ..., t_{n}$. Your task is to calculate for how many minutes Limak will watch the game.
|
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 case at the beginning. Also, you can assume that $t_{n + 1} = 91$ or $t_{n + 1} = 90$ (both should work - do you see why?). If your program haven't found two consecutive numbers different by more than $15$ then print $90$. If you still have problems to solve this problem then check codes of other participants.
|
[
"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 each division should be non-empty.
- Each problem should be used in exactly one division (yes, it is unusual requirement).
- Each problem used in division 1 should be harder than any problem used in division 2.
- If two problems are similar, they should be used in different divisions.
Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.
Note, that the relation of similarity \textbf{is not} transitive. That is, if problem $i$ is similar to problem $j$ and problem $j$ is similar to problem $k$, it doesn't follow that $i$ is similar to $k$.
|
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}$ and $b_{i}$. In other words, it must be on the right from $a_{i}$ and on the left from $b_{i}$. For each pair if $a_{i} > b_{i}$ then we swap these two numbers. Now, the splitting place must be on the right from $a_{1}, a_{2}, ..., a_{m}$, so it must be on the right from $A = max(a_{1}, a_{2}, ..., a_{m})$. In linear time you can calculate $A$, and similarly calculate $B = min(b_{1}, ..., b_{m})$. Then, the answer is $B - A$. It may turn out that $A > B$ though but we don't want to print a negative answer. So, we should print $max(0, B - A)$.
|
[
"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));
return 0;
}
|
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 sequence, that is, there exists a positive integer $i$, such that $s_{i} = b$. Of course, you are the person he asks for a help.
|
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$, and different cells may contain either different or equal integers.
- The sum of integers in each of four squares $2 × 2$ is equal to the sum of integers in the top left square $2 × 2$.
- Four elements $a$, $b$, $c$ and $d$ are known and are located as shown on the picture below.
Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to $0$, meaning Vasya remembers something wrong.
Two squares are considered to be different, if there exists a cell that contains two different integers in different squares.
|
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 + a + m = y + c + a + m$ and $y = x + b - c$. Similarly, $z = x + a - d$ and $w = a + y - d = z + b - c$. This square is legal if $1 \le y, z, w \le n$. We should just check it. Also we can solve this problem in $O(1)$.
|
[
"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 <= n) {
ans++;
}
}
ans *= n;
cout << ans << endl;
}
|
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, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any \textbf{neighbouring} bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
|
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 zero with $l - 1$ operations. So, if we sum number of operations in each part we get $ans = n - k$ where $k$ is number of parts. We should maximize $k$ to get the optimal answer. One of the part consists of some prefix and probably some suffix. Each of other parts is subarray of $a$. Let's calculate prefix sums. Each part has zero sum so prefix sums before each part-subarray are the same. So we can calculate $f$ - number of occurencies of the most frequent number in prefix sums and answer will be equal to $n - f$. Bonus: how to hack solutions with overflow?
|
[
"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]++;
ans = min(ans, n - d[sum]);
}
cout << ans << endl;
}
|
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 the formal description of the construction process.
- First element $a_1$ becomes the root of the tree.
- Elements $a_2, a_3, \ldots, a_n$ are added one by one. To add element $a_i$ one needs to traverse the tree starting from the root and using the following rules:
- The pointer to the current node is set to the root.
- If $a_i$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node.
- If at some point there is no required child, the new node is created, it is assigned value $a_i$ and becomes the corresponding child of the current node.
|
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::set and upper_bound in C++. We should keep sorted tree traversal (it's property of BST). So $x$ must be right child of vertex with $l$ or left child of vertex with $r$. Let $l$ hasn't right child and $r$ hasn't left child. Hence lowest common ancestor (lca) of $l$ and $r$ doesn't equal to $l$ or $r$. So lca is between $l$ and $r$ in tree traversal. But it's impossible because $l$ is maximal possible and $r$ is minimal possible. So $l$ has right child or $r$ has left child and we know exactly which of them will be parent of $x$. That's all. Time complexity is $O(n\log n)$.
|
[
"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;
auto it = numbers.upper_bound(v);
int result;
if (it != numbers.end() && left.count(*it) == 0) {
left[*it] = v;
result = *it;
} else {
it--;
right[*it] = v;
result = *it;
}
numbers.insert(v);
cout << result;
if (i == n - 2) cout << 'n';
else cout << ' ';
}
}
|
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 $i$ to station $j$. As Vasya is fond of different useless statistic he asks you to compute the sum of all values $ρ_{i, j}$ among all pairs $1 ≤ i < j ≤ n$.
|
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 find $m$ with segment tree or binary indexed tree or sparse table. Now answer equals to sum of all $dp_{i}$.
|
[
"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, int r) {
pair<int, int> ans{-1, -1};
for (l += maxn, r += maxn + 1; l < r; l >>= 1, r >>= 1) {
if (l & 1) ans = max(ans, tree[l++]);
if (r & 1) ans = max(ans, tree[--r]);
}
return ans.second;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int n;
cin >> n;
vector<int> a(n);
a[n - 1] = n - 1;
for (int i = 0; i < n - 1; i++) {
cin >> a[i];
a[i]--;
}
build(a, n);
vector<long long> dp(n);
long long ans = 0;
dp[n - 1] = 0;
for (int i = n - 2; i >= 0; i--) {
int m = get(i + 1, a[i]);
dp[i] = dp[m] - (a[i] - m) + n - i - 1;
ans += dp[i];
}
cout << ans << 'n';
}
|
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 to maximize the distance between the minimum and the maximum elements. The distance between two elements is considered to be equal to the absolute difference between their positions.
|
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 level (counting from the top), then $3$ glasses on the third level and so on.The bottom level consists of $n$ glasses.
Vlad has seen in the movies many times how the champagne beautifully flows from top levels to bottom ones, filling all the glasses simultaneously. So he took a bottle and started to pour it in the glass located at the top of the pyramid.
Each second, Vlad pours to the top glass the amount of champagne equal to the size of exactly one glass. If the glass is already full, but there is some champagne flowing in it, then it pours over the edge of the glass and is equally distributed over two glasses standing under. If the overflowed glass is at the bottom level, then the champagne pours on the table. For the purpose of this problem we consider that champagne is distributed among pyramid glasses immediately. Vlad is interested in the number of completely full glasses if he stops pouring champagne in $t$ seconds.
Pictures below illustrate the pyramid consisting of three levels.
|
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 following case: if in the current wineglass is more champagne than its volume, let's make $surplus = V_{tek} - 2^{n}$, and add $surplus / 2$ of champagne in each of the two bottom wineglasses. Asymptotic behavior $O(n^{2})$.
|
[
"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 original string. What is the maximum beauty of the string he can achieve?
|
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 the answer with length of this substring and move $l$ to the right. $$ Asymptotic behavior $O(n * alphabet)$.
|
[
"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 doesn't change its position in the labyrinth. Also, each block has some number of doors (possibly none). In one minute, Theseus can either push the button in order to rotate all the blocks $90$ degrees clockwise or pass to the neighbouring block. Theseus can go from block $A$ to some neighbouring block $B$ only if block $A$ has a door that leads to block $B$ and block $B$ has a door that leads to block $A$.
Theseus found an entrance to labyrinth and is now located in block $(x_{T}, y_{T})$ — the block in the row $x_{T}$ and column $y_{T}$. Theseus know that the Minotaur is hiding in block $(x_{M}, y_{M})$ and wants to know the minimum number of minutes required to get there.
Theseus is a hero, not a programmer, so he asks you to help him.
|
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 length of the minimum path if such exists. Asymptotic behavior $O(n * m)$.
|
[
"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 polynomial
\[
P(x) = a_{n}x^{n} + a_{n - 1}x^{n - 1} + ... + a_{1}x + a_{0},
\]
with yet undefined coefficients and the integer $k$. Players alternate their turns. At each turn, a player pick some index $j$, such that coefficient $a_{j}$ that stay near $x^{j}$ is not determined yet and sets it to \textbf{any} value (integer or real, positive or negative, $0$ is also allowed). Computer moves first. The human will be declared the winner if and only if the resulting polynomial will be divisible by $Q(x) = x - k$.Polynomial $P(x)$ is said to be divisible by polynomial $Q(x)$ if there exists a representation $P(x) = B(x)Q(x)$, where $B(x)$ is also some polynomial.
Some moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally?
|
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 known then win who make the move. Case when $k \neq 0$. Here we have two cases: all coefficients already known. Then we need to check $x = k$ - is it the root of the given polynomial. Otherwise who will make the last move will win. Let we know all coefficient except one. Let this coefficient is the coefficient before $x^{i}$. Let $C_{1}$ is the sum for all $j \neq i$ $a_{j}k^{ j}$ and $C_{2} = k^{ i} \neq 0$. Then we have the equation $a_{i} * C_{2} = - C_{1}$ which always have the solution. If the human will make the last move he need to write the root to the place of the coefficient, otherwise computer will write any number, but not the root. Asymptotic behavior $O(n)$.
|
[
"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 of the $i$-th person is equal to $a_{i}$.
Consider the width of the person walking as usual to be equal to $1$, while the width of the bent person is equal to $2$. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
|
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.
Vanya has $n$ pieces of potato, the height of the $i$-th piece is equal to $a_{i}$. He puts them in the food processor one by one starting from the piece number $1$ and finishing with piece number $n$. Formally, each second the following happens:
- If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
- Processor smashes $k$ centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
|
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 we will waste $a[i] / k$ seconds on it. If we can not put this piece of potato after that, we will waste $1$ more second to smash everything, that inside, else just put this piece. We will get an answer same as we could get with actions from the statement. Complexity $O(n)$.
|
[
"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 += cur_h/k;
cur_h %= k;
ans += (cur_h>0);
cout << ans << endl;
return 0;
}
|
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 their bitwise AND is equal to $s$. As this number can be large, output it modulo $10^{9} + 7$.
To represent the string as a number in numeral system with base $64$ Vanya uses the following rules:
- digits from '0' to '9' correspond to integers from $0$ to $9$;
- letters from 'A' to 'Z' correspond to integers from $10$ to $35$;
- letters from 'a' to 'z' correspond to integers from $36$ to $61$;
- letter '-' correspond to integer $62$;
- letter '_' correspond to integer $63$.
|
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 $nullbits$ - is amount of zero bits. Complexity $O(|s|)$.
|
[
"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++)
pattern.push_back(i);
for (char i = 'a'; i <= 'z'; i++)
pattern.push_back(i);
pattern.push_back('-');
pattern.push_back('_');
for (i = 0; i < 64; i++)
symbol_val[pattern[i]] = i;
ll ans = 1;
for (i = 0; i < s.size(); i++)
{
ll x = symbol_val[s[i]];
for (j = 0; j < 6; j++)
if ((x&(1<<j)) == 0)
ans = (ans*3)%MOD;
}
cout << ans << endl;
return 0;
}
|
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 locked. There is exactly one chest of type $p$ and it contains a treasure.
Vanya starts in cell $(1, 1)$ (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell $(r_{1}, c_{1})$ (the cell in the row $r_{1}$ and column $c_{1}$) and $(r_{2}, c_{2})$ is equal to $|r_{1} - r_{2}| + |c_{1} - c_{2}|$.
|
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 cell of color $color$ with coordinates $(x1, y1)$ and for each cell with color $color - 1$ and coordinates $(x2, y2)$ $dp[x1][y1] = dp[x2][y2] + abs(x1 - x2) + abs(y1 - y2)$. But complexity of this solution is $O(n^{2} \cdot m^{2})$, what is not enough. We can do such improvement: let $cnt[x]$ be the amount of cells of color $x$, then when $cnt[color] \cdot cnt[color - 1] \ge n \cdot m$, we can do bfs from cells of color $color - 1$ to cells of color $color$. Then we will have complexity $O(n \cdot m \cdot sqrt(n \cdot m))$. Proof There also exists solution with 2D segment tree:
|
[
"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][2005][2005];
ll dir[4][2] = {{-1,0},{1,0},{0,1},{0,-1}};
vector<pair<ll,ll> > g[250505];
vector<pair<ll, pair<ll,ll> > > lst, bfs;
ll Abs(ll x)
{
return x>0?x:-x;
}
ll find_dist(ll x1, ll y1, ll x2, ll y2)
{
return Abs(x1-x2) + Abs(y1-y2);
}
bool in_range(ll x, ll y)
{
return (x >= 0 && x < y);
}
int get (int lx, int rx, int ly, int ry) {
rx++;
ry++;
int res = MOD;
ll l = ly, r = ry;
for (lx += N, rx += N; lx < rx; lx >>= 1, rx >>= 1) {
if (rx&1)
{
ly = l; ry = r;
rx--;
for (ly += N, ry += N; ly < ry; ly >>= 1, ry >>= 1) {
if (ly&1)
{
res = min(res, t[glob][rx][ly]);
ly++;
}
if (ry&1)
{
--ry;
res = min(res, t[glob][rx][ry]);
}
}
}
if (lx&1)
{
ly = l; ry = r;
for (ly += N, ry += N; ly < ry; ly >>= 1, ry >>= 1) {
if (ly&1)
{
res = min(res, t[glob][lx][ly]);
ly++;
}
if (ry&1)
{
--ry;
res = min(res, t[glob][lx][ry]);
}
}
lx++;
}
}
return res;
}
void update (int x, int y, int val) {
ll tmp = y;
t[glob][x+N][tmp+N] = val;
for (x += N; x > 1; x >>= 1)
{
y = tmp;
for (y += N; y > 1; y >>= 1)
{
t[glob][x][y>>1] = min(t[glob][x][y], t[glob][x][y^1]);
t[glob][x>>1][y] = min(t[glob][x][y], t[glob][x^1][y]);
}
t[glob][x>>1][y] = min(t[glob][x][y], t[glob][x^1][y]);
}
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
cin >> n >> m >> p;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
dp[i][j] = MOD;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
{
scanf("%d", &a[i][j]);
g[a[i][j]].push_back(mp(i,j));
if (a[i][j] == 1)
dp[i][j] = i+j;
if (a[i][j] == p)
fx = i, fy = j;
}
for (i = 0; i <= N*2; i++)
for (j = 0; j <= N*2; j++)
for (k = 0; k < 4; k++)
t[k][i][j] = MOD;
//UR - dp[x2][y2] = dp[x1][y1] + x2-x1+y2-y1 = dp[x1][y1]-x1-y1+(x2+y2)
//UL - dp[x2][y2] = dp[x1][y1] + x2-x1+y1-y2 = dp[x1][y1]-x1+y1+(x2-y2)
//DR - dp[x2][y2] = dp[x1][y1] + x1-x2+y2-y1 = dp[x1][y1]-y1+x1+(y2-x1)
//DL - dp[x2][y2] = dp[x1][y1] + x1-x2+y1-y2 = dp[x1][y1]+x1+y1+(-x2-y2)
for (i = 2; i <= p; i++)
{
ll last_sz = g[i-1].size();
for (j = 0; j < last_sz; j++)
{
ll x = g[i-1][j].X;
ll y = g[i-1][j].Y;
glob = 0;
//cout << x << " " << y << " " << get( 0, x, 0, y) << "g" << endl;
update(x,y,dp[x][y]-x-y);
//cout << get( 0, x, 0, y) << "f" << endl;
glob = 1;
update(x,y,dp[x][y]-x+y);
glob = 2;
update(x,y,dp[x][y]+x-y);
glob = 3;
update(x,y,dp[x][y]+x+y);
}
ll cur_sz = g[i].size();
for (j = 0; j < cur_sz; j++)
{
ll x = g[i][j].X;
ll y = g[i][j].Y;
glob = 0;
//cout << get( 0, x, 0, y) << endl;
dp[x][y] = min(dp[x][y], get( 0, x, 0, y)+x+y);
glob = 1;
dp[x][y] = min(dp[x][y], get(0, x, y, m-1)+x-y);
glob = 2;
dp[x][y] = min(dp[x][y], get(x, n-1, 0, y)-x+y);
glob = 3;
dp[x][y] = min(dp[x][y], get(x, n-1, y, m-1)-x-y);
}
for (j = 0; j < last_sz; j++)
{
ll x = g[i-1][j].X;
ll y = g[i-1][j].Y;
glob = 0;
update(x,y,MOD);
glob = 1;
update(x,y,MOD);
glob = 2;
update(x,y,MOD);
glob = 3;
update(x,y,MOD);
}
}
/*for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
cout << dp[i][j] << " ";
cout << endl;
}*/
cout << dp[fx][fy] << endl;
return 0;
}
|
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:
\begin{verbatim}
**o**
**o**
ooooo
**o**
**o**
\end{verbatim}
or
\begin{verbatim}
o***o
*o*o*
**o**
*o*o*
o***o
\end{verbatim}
Formally, the cross is given by three integers $r$, $c$ and $d$, such that $d ≤ r, c ≤ n - d + 1$. The normal cross consists of balloons located in cells $(x, y)$ (where $x$ stay for the number of the row and $y$ for the number of the column), such that $|x - r|·|y - c| = 0$ and $|x - r| + |y - c| < d$. Rotated cross consists of balloons located in cells $(x, y)$, such that $|x - r| = |y - c|$ and $|x - r| < d$.
Vanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo $10^{9} + 7$.
|
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 non-zero balloons are right to cell $(x, y)$, we can create an array $p[x][y]$, where $p[x][y] = p[x][y - 1] + 1$ if $a[x][y]! = 0$ else $p[x][y] = 0$ So now we can for each cell $(x, y)$ we can find the maximum size of cross with the centre in this cell, that will not contain zeros. We can compare product for crosses with centers in the cells $(x, y)$ and radius $r$ using logarythms. For example, if we need to compare 2 crosses with values $x_{1} \cdot x_{2} \cdot ... \cdot x_{n}$ and $y_{1} \cdot y_{2} \cdot ... \cdot y_{m}$, we can compare $log(x_{1} \cdot x_{2} \cdot ... \cdot x_{n})$ and $log(y_{1} \cdot y_{2} \cdot ... \cdot y_{n})$, what will be equivalent to comparing $log(x_{1}) + log(x_{2}) + ... + log(x_{n})$ and $log(y_{1}) + log(y_{2}) + ... + log(y_{m})$. We can also use partial sum arrays to find value $log(x_{1}) + log(x_{2}) + ... + log(x_{n})$ for each cross, so we can find the product of the values in each cross for $O(1)$ time. Complexity $O(n^{2})$.
|
[
"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},{-1,1},{1,-1},{1,1},{1,0},{0,1},{-1,0},{0,-1}};
char a[N][N];
bool in_range(ll x)
{
return (x >= 0 && x < n);
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
lg2 = log(2);
lg3 = log(3);
cin >> n;
for (i = 0; i < n; i++)
scanf("%s",a[i]);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (a[i][j] == '3')
logs[i][j] = lg3;
else if (a[i][j] == '2')
logs[i][j] = lg2;
for (dir = 0; dir < 8; dir++)
{
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (!in_range(i-directions[dir][0]) || !in_range(j-directions[dir][1]))
{
k = 0;
ll d1 = directions[dir][0], d2 = directions[dir][1];
for (x = i, y = j; in_range(x) && in_range(y); x += d1, y += d2)
{
if (a[x][y] != '0')
{
k++;
if (x == i && y == j)
sums[dir][x][y] = logs[i][j];
else
sums[dir][x][y] = sums[dir][x-d1][y-d2] + logs[x][y];
}
else
{
sums[dir][x][y] = 0;
k = 0;
}
pre[dir][x][y] = k;
}
}
}
ans = -1;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (a[i][j] != '0')
{
ll tmp = n+5;
for (k = 0; k < 4; k++)
tmp = min(tmp, pre[k][i][j]);
double val = logs[i][j];
for (k = 0; k < 4; k++)
val += sums[k][i+directions[k][0]*(tmp-1)][j+directions[k][1]*(tmp-1)] - sums[k][i][j];
if (val > ans)
{
ans = val;
ansx = i;
ansy = j;
anssize = tmp;
ansdir = 0;
}
tmp = n+5;
for (k = 4; k < 8; k++)
tmp = min(tmp, pre[k][i][j]);
val = logs[i][j];
for (k = 4; k < 8; k++)
val += sums[k][i+directions[k][0]*(tmp-1)][j+directions[k][1]*(tmp-1)] - sums[k][i][j];
if (val > ans)
{
ans = val;
ansx = i;
ansy = j;
anssize = tmp;
ansdir = 4;
}
}
total = a[ansx][ansy]-'0';
for (k = ansdir; k < ansdir+4; k++)
{
for (i = 1; i < anssize; i++)
total = (total*(a[ansx+directions[k][0]*i][ansy+directions[k][1]*i]-'0'))%MOD;
}
cout << total << endl;
return 0;
}
|
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 Taylor to find that year.
Note that leap years has $366$ days. The year is leap if it is divisible by $400$ or it is divisible by $4$, but not by $100$ (https://en.wikipedia.org/wiki/Leap_year).
|
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 by two. Complexity: $O(1)$ - easy to see that we will not iterate more than some small fixed constant times.
|
[
"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 divisible by $a$ and $b$ can be either painted Red or Blue.
After her painting is done, she will get $p$ chocolates for each tile that is painted Red and $q$ chocolates for each tile that is painted Blue.
Note that she can paint tiles in any order she wants.
Given the required information, find the maximum number of chocolates Joty can get.
|
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{\eta}|\bar{\eta}|\langle\bar{\cal J},\langle\psi\rangle\right|\left|\frac{\bar{\eta}}{|q\bar{\eta}|\bar{\theta}\cdot\bar{\theta}|}\right|$. Complexity: $O(log(max(a, b)))$.
|
[
"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 other using linear function, we can use binary matrix exponentiation. There is only one variable $x$ in our problem. The new variable $x'$ is calculating using formula $A \cdot x + B$. Consider the matrix $z = [[A, B], [0, 1]]$ and the vector $v = [0, 1]$. Let's multiply $z$ and $v$. Easy to see that we will get the vector $v' = [x', 1]$. So to make $n$ iterations we should multiply $z$ and $v$ $n$ times. We can do that using binary matrix exponentiation, because matrix multiplication is associative. As an exercise try to write down the matrix for the Fibonacci numbers and calculate the $n$-th Fibonacci number in $O(logn)$ time. The matrix and the vector is under the spoiler. z=[[0, 1], [1, 1]], v=[0, 1]. Complexity: $O(logn)$.
|
[
"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[2][2], int b[2][2]) {
static int res[2][2];
forn(i, 2)
forn(j, 2) {
res[i][j] = 0;
forn(k, 2) inc(res[i][j], mul(a[i][k], b[k][j]));
}
forn(i, 2) forn(j, 2) a[i][j] = res[i][j];
}
void bin_pow(int a[2][2], li b) {
static int res[2][2];
forn(i, 2) forn(j, 2) res[i][j] = i == j;
while (b) {
if (b & 1) mul(res, a);
mul(a, a);
b >>= 1;
}
forn(i, 2) forn(j, 2) a[i][j] = res[i][j];
}
void solve() {
int z[2][2] = {
{ A, B },
{ 0, 1 }
};
bin_pow(z, n);
int result = add(mul(z[0][0], x), z[0][1]);
cout << result << endl;
}
|
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 battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.
Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.
|
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 a s k}^{n}(z_{m a s k\cup j,i}\cdot p_{i j}+z_{m a s k\cup j,j}\cdot p_{j i})$. Time complexity: $O(2^{n}n^{2})$. Memory complexity: $O(2^{n}n)$.
|
[
"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;
forn(j, n)
if (!(mask & (1 << j))) {
ld cur = 0;
cur += solve(mask | (1 << j), i) * p[i][j];
cur += solve(mask | (1 << j), j) * p[j][i];
ans = max(ans, cur);
}
return ans;
}
void solve() {
if (n == 1) {
puts("1");
return;
}
forn(i, 1 << n) forn(j, n) z[i][j] = -1;
ld ans = 0;
forn(i, n)
forn(j, i) {
int mask = (1 << i) | (1 << j);
ld cur = 0;
cur += solve(mask, i) * p[i][j];
cur += solve(mask, j) * p[j][i];
ans = max(ans, cur);
}
cout << ans << endl;
}
|
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 $q$ find the maximal value $x·q + y$ over all pairs $(x, y)$ from the set.
Help Lena to process the queries.
|
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. Let's build the lower envelope by that lines. Now to calculate the answer to the query we should get maximum over the lines from the envelope and the lines from the block before the current query that is not deleted yet. There are no more than $\sqrt{n}$ lines from the block, so we can iterate over them. Let's find the answers from the envelope for all queries of the third type from the block at once: we should sort them and iterate over envelope using two pointers technique. Complexity: $O(n{\sqrt{n}})$.
|
[
"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] == 3) {
assert(scanf("%d", &q[i]) == 1);
} else throw;
}
return true;
}
bool in_set[N], deleted[N];
vector<pair<pti, int>> lines;
vector<pti> envelope;
void build_envelope() {
envelope.clear();
envelope.reserve(n);
forn(ii, sz(lines)) {
int i = lines[ii].y;
if (in_set[i] && !deleted[i]) {
assert(t[i] == 1);
pti c(a[i], b[i]);
while (!envelope.empty()) {
pti b = envelope.back();
if (b.x == c.x) {
envelope.pop_back();
continue;
} else if (sz(envelope) > 1) {
pti a = envelope[sz(envelope) - 2];
ld xc = ld(c.y - a.y) / (a.x - c.x);
ld xb = ld(b.y - a.y) / (a.x - b.x);
if (xc < xb) {
envelope.pop_back();
continue;
}
}
break;
}
envelope.pb(c);
}
}
}
li ans[N];
vector<pti> qs;
void process_qs() {
sort(all(qs));
int p = 0;
forn(i, sz(qs)) {
li q = qs[i].x;
int id = qs[i].y;
while (p + 1 < sz(envelope)) {
li cval = envelope[p].x * q + envelope[p].y;
li nval = envelope[p + 1].x * q + envelope[p + 1].y;
if (cval > nval) break;
p++;
}
if (p < sz(envelope)) {
ans[id] = envelope[p].x * q + envelope[p].y;
}
}
}
void solve() {
lines.clear();
lines.reserve(n);
forn(i, n) if (t[i] == 1) lines.pb(mp(mp(a[i], b[i]), i));
sort(all(lines));
memset(in_set, false, sizeof(in_set));
memset(deleted, false, sizeof(deleted));
forn(i, n) ans[i] = LLONG_MIN;
int blen = int(sqrtl(n));
blen = 2500;
for (int l = 0; l < n; l += blen) {
int r = min(n, l + blen);
memset(deleted, false, sizeof(deleted));
fore(i, l, r) if (t[i] == 2) deleted[id[i]] = true;
build_envelope();
qs.clear();
qs.reserve(r - l);
fore(i, l, r) if (t[i] == 3) qs.pb(mp(q[i], i));
process_qs();
fore(i, l, r) {
if (t[i] == 1) in_set[i] = true;
else if (t[i] == 2) in_set[id[i]] = false;
else {
fore(j, l, r) {
if (t[j] == 1 && in_set[j])
ans[i] = max(ans[i], li(a[j]) * q[i] + b[j]);
else if (t[j] == 2 && in_set[id[j]])
ans[i] = max(ans[i], li(a[id[j]]) * q[i] + b[id[j]]);
}
if (ans[i] != LLONG_MIN) printf("%lldn", ans[i]);
else puts("EMPTY SET");
}
}
}
}
|
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 two distinct divisors, $1$ and $x$. If integer $x > 1$ is not prime, it's called composite.
You can ask up to $20$ queries about divisors of the hidden number. In each query you should print an integer from interval $[2, 100]$. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".
For example, if the hidden number is $14$ then the system will answer "yes" only if you print $2$, $7$ or $14$.
When you are done asking queries, print "prime" or "composite" and terminate your program.
You will get the Wrong Answer verdict if you ask more than $20$ queries, or if you print an integer not from the range $[2, 100]$. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.
You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).
|
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 two distinct prime divisors $p$ and $q$ then both of them are at most $50$ - otherwise the hidden number would be bigger than $100$ (because for $p \ge 2$ and $q > 50$ we would get $p \cdot q > 100$). So, it's enough to check primes up to $50$ (there are $15$ of them), and check if at least two of them are divisors.
|
[
"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:
print(ele)
stdout.flush()
x = input()
if x == "yes":
yes += 1
print("prime" if yes < 2 else "composite")
|
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_{1}^{3} + a_{2}^{3} + ... + a_{k}^{3}$.
Limak is going to build a tower. First, he asks you to tell him a positive integer $X$ — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed $X$.
Limak asks you to choose $X$ not greater than $m$. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize $X$.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum $X ≤ m$ that results this number of blocks.
|
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 cases and see that the first block with side $(a - 2)^{3}$ must be a worse choice than $(a - 1)^{3}$. It's because we start with smaller $X$ and we are left with smaller $m_{2}$. The situation for even smaller side of the first block would be even worse. Now, you can notice that the answer will be small. From $m$ of magnitude $a^{3}$ after one block we get $m_{2}$ of magnitude $a^{2}$. So, from $m$ we go to $m^{2 / 3}$, which means that the answer is $O(loglog(m))$. The exact maximum answer turns out to be $18$. The intended solution is to use the recursion and brutally check both cases: taking $a^{3}$ and taking $(a - 1)^{3}$ where $a$ is maximum that $a^{3} \le m$. It's so fast that you can even find $a$ in $O(m^{1 / 3})$, increasing $a$ by one.
|
[
"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, q1) = go(x - X[i]);
tie(p2, q2) = go(X[i] - 1);
return M[x] = max(make_pair(p1+1, q1+X[i]), {p2, q2});
}
int main()
{
for(int i=0; i<=1e5+7; i++)
X.push_back(1LL*i*i*i);
ll x;
cin >> x;
int a;
long long b;
tie(a,b) = go(x);
cout << a << " " << b << "n";
}
|
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 empty cells that starts with $(r_{1}, c_{1})$, finishes with $(r_{2}, c_{2})$, and any two consecutive cells in this sequence are directly connected. A connected component is a set of empty cells such that any two cells in the component are connected, and there is no cell in this set that is connected to some cell not in this set.
Your friend Limak is a big grizzly bear. He is able to destroy any obstacles in some range. More precisely, you can choose a square of size $k × k$ in the grid and Limak will transform all blocked cells there to empty ones. However, you can ask Limak to help only once.
The chosen square must be completely inside the grid. It's possible that Limak won't change anything because all cells are empty anyway.
You like big connected components. After Limak helps you, what is the maximum possible size of the biggest connected component in the grid?
|
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 CC's we should only count their cells that are outside of the square - not to count something twice. We will move a square, and at the same time for each CC we will keep the number of its cells outside the square. We will used a sliding-window technique. Let's fix row of the grid - the upper row of the square. Then, we will first place the square on the left, and then we will slowly move a square to the right. As we move a square, we should iterate over cells that stop or start to belong to the square. For each such empty cell we should add or subtract $1$ from the size of its CC (ids and sizes of CC's were found at the beginning). And for each placement we consider, we should iterate over outside borders of the square ($4k$ cells - left, up, right and down side) and sum up sizes of CC's touching our square. Be careful to not count some CC twice - you can e.g. keep an array of booleans and mark visited CC's. After checking all $4k$ cells you should clear an array, but you can't do it in O(number_of_all_components) because it would be too slow. You can e.g. also add visited CC's to some vector, and later in the boolean array clear only CC's from the vector (and then clear vector). The complexity is $O(n^{2} \cdot k)$.
|
[
"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;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author AlexFetisov
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE_356 solver = new TaskE_356();
solver.solve(1, in, out);
out.close();
}
static class TaskE_356 {
int n;
int k;
boolean[][] f;
List<Integer> componentCellCount;
int[][] color;
int x = 0;
int y = 0;
int totalEmpty = 0;
int sumInComponents = 0;
int[] amInComponents;
int[] flag;
int currentFlagColor = 0;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
k = in.nextInt();
f = new boolean[n][n];
color = new int[n][n];
ArrayUtils.fill(color, -1);
for (int i = 0; i < n; ++i) {
char[] c = in.nextString().toCharArray();
for (int j = 0; j < n; ++j) {
f[i][j] = (c[j] == '.');
}
}
// Caclulate all CC
int res = 0;
componentCellCount = new ArrayList<Integer>();
int currentComponentId = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (color[i][j] == -1) {
int count = dfs(i, j, currentComponentId++);
componentCellCount.add(count);
res = Math.max(res, count);
}
}
}
flag = new int[currentComponentId];
amInComponents = new int[currentComponentId];
// Preprocess first square
for (int i = 0; i < k; ++i) {
for (int j = 0; j < k; ++j) {
addCell(i, j);
}
}
res = Math.max(res, checkResult());
for (int i = 0; i <= n - k; ++i) {
int delta = i % 2 == 0 ? 1 : -1;
for (int j = 0; j < n - k; ++j) {
moveSquare(0, x, y, x, y + delta);
y += delta;
res = Math.max(res, checkResult());
}
if (i != n - k) {
moveSquare(1, x, y, x + 1, y);
++x;
res = Math.max(res, checkResult());
}
}
out.println(res);
}
void moveSquare(int type, int cx, int cy, int nx, int ny) {
if (type == 0) {
if (ny < cy) {
for (int i = 0; i < k; ++i) {
removeCell(cx + i, cy + k - 1);
addCell(cx + i, ny);
}
} else {
for (int i = 0; i < k; ++i) {
removeCell(cx + i, cy);
addCell(cx + i, ny + k - 1);
}
}
} else {
for (int i = 0; i < k; ++i) {
removeCell(cx, cy + i);
addCell(nx + k - 1, cy + i);
}
}
}
void removeCell(int cx, int cy) {
if (f[cx][cy]) {
--totalEmpty;
amInComponents[color[cx][cy]]--;
if (amInComponents[color[cx][cy]] == 0) {
sumInComponents -= componentCellCount.get(color[cx][cy]);
}
}
}
void addCell(int cx, int cy) {
if (f[cx][cy]) {
++totalEmpty;
amInComponents[color[cx][cy]]++;
if (amInComponents[color[cx][cy]] == 1) {
sumInComponents += componentCellCount.get(color[cx][cy]);
}
}
}
int dfs(int cx, int cy, int cId) {
if (cx < 0 || cx >= n || cy < 0 || cy >= n) return 0;
if (color[cx][cy] != -1) return 0;
if (!f[cx][cy]) return 0;
color[cx][cy] = cId;
int am = 1;
am += dfs(cx - 1, cy, cId);
am += dfs(cx + 1, cy, cId);
am += dfs(cx, cy - 1, cId);
am += dfs(cx, cy + 1, cId);
return am;
}
int checkResult() {
++currentFlagColor;
int res = k * k - totalEmpty + sumInComponents;
for (int i = 0; i < k; ++i) {
res += checkCell(x - 1, y + i);
res += checkCell(x + k, y + i);
res += checkCell(x + i, y - 1);
res += checkCell(x + i, y + k);
}
return res;
}
int checkCell(int cx, int cy) {
if (cx < 0 || cx >= n || cy < 0 || cy >= n) return 0;
if (!f[cx][cy]) return 0;
if (amInComponents[color[cx][cy]] > 0) return 0;
if (flag[color[cx][cy]] == currentFlagColor) return 0;
flag[color[cx][cy]] = currentFlagColor;
return componentCellCount.get(color[cx][cy]);
}
}
static class ArrayUtils {
public static void fill(int[][] f, int value) {
for (int i = 0; i < f.length; ++i) {
Arrays.fill(f[i], value);
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
}
|
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$ is defined as the minimum number of roads used to travel between $a$ and $b$.
Limak is a grizzly bear. He is a criminal and your task is to catch him, or at least to try to catch him. You have only two days (today and tomorrow) and after that Limak is going to hide forever.
Your main weapon is BCD (Bear Criminal Detector). Where you are in some city, you can use BCD and it tells you the distance between you and a city where Limak currently is. Unfortunately, BCD can be used only once a day.
You don't know much about Limak's current location. You assume that he is in one of $n$ cities, chosen uniformly at random (each city with probability $\textstyle{\frac{1}{n}}$). You decided for the following plan:
- Choose one city and use BCD there.
- After using BCD you can try to catch Limak (but maybe it isn't a good idea). In this case you choose one city and check it. You win if Limak is there. Otherwise, Limak becomes more careful and you will never catch him (you loose).
- Wait $24$ hours to use BCD again. You know that Limak will change his location during that time. In detail, he will choose uniformly at random one of roads from his initial city, and he will use the chosen road, going to some other city.
- Tomorrow, you will again choose one city and use BCD there.
- Finally, you will try to catch Limak. You will choose one city and check it. You will win if Limak is there, and loose otherwise.
Each time when you choose one of cities, you can choose any of $n$ cities. Let's say it isn't a problem for you to quickly get somewhere.
What is the probability of finding Limak, if you behave optimally?
|
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 there in the second day (details in my code below). Also, in a vector interesting let's store all cities that are at distance $d1$ from city $g1$. Then, iterate over all $g2$ - the second city in which you use the BCD. For cities from interesting, we want to iterate over them and for each distinct distance from $g2$ to choose the biggest probability (because we will make the best guess there is). Magic: the described approach has four loops (one in the other) but it's $O(n^{3})$. Proof is very nice and I encourage you to try to get it yourself. After fixing g1 divide cities by their distance from g1. Then, when we get distance d1 in the first day, then in the second day all possible cities are at distance d1-1, d1 and d1+1. So, we will consider each city at most three times.
|
[
"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);
}
T consider_tomorrow(int n, int g1, int dist1) {
T best_tomorrow = 0;
// we need complexity O(n * x)
// where x denotes the number of v that |dist1-dist[g1][v]| <= 1
for(int i = 1; i <= n; ++i) {
p_later[i] = 0;
vis[i] = false;
}
vector<int> interesting;
for(int v = 1; v <= n; ++v) if(dist[g1][v] == dist1)
for(int b : w[v]) {
// Limak started in v with prob. 1/n
// he then moved to b with prob. 1/degree[v]
p_later[b] += (T) 1 / n / w[v].size();
if(!vis[b]) {
vis[b] = true;
interesting.push_back(b);
}
}
// interesting.size() <= x, where x is defined above (needed for complexity)
for(int g2 = 1; g2 <= n; ++g2) {
T local_sum = 0; // over situations with fixed g1, dist1, g2
for(int b : interesting)
max_self(p_dist_max[dist[g2][b]], p_later[b]);
for(int b : interesting) {
local_sum += p_dist_max[dist[g2][b]];
p_dist_max[dist[g2][b]] = 0; // so it won't be calculated twice
}
max_self(best_tomorrow, local_sum);
}
return best_tomorrow;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
FOR(i,1,n) FOR(j, 1, n) if(i != j)
dist[i][j] = n + 1; // infinity
FOR(i,1,m) {
int a, b;
scanf("%d%d", &a, &b);
w[a].push_back(b);
w[b].push_back(a);
dist[a][b] = dist[b][a] = 1;
}
// Floyd-Warshall
FOR(b,1,n)FOR(a,1,n)FOR(c,1,n)
dist[a][c] = min(dist[a][c], dist[a][b] + dist[b][c]);
// g1 is the first guess
T answer = 0;
FOR(g1, 1, n) {
T sum_over_dist1 = 0;
FOR(dist1, 0, n) {
int cnt_cities = 0;
FOR(i, 1, n) if(dist[g1][i] == dist1)
++cnt_cities;
if(cnt_cities == 0) continue; // there are no cities within distance dist1
// 1) consider guessing immediately
T immediately = (T) 1 / n; // how much it counts towards the answer
// 2) consider waiting for tomorrow
T second_day = consider_tomorrow(n, g1, dist1);
sum_over_dist1 += max(immediately, second_day);
}
max_self(answer, sum_over_dist1);
}
printf("%.12lfn", (double) answer);
return 0;
}
|
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 separate line.
- 2 a b x — for $i\in[a,b]$ set $t_{i}$ to $x$. It's guaranteed that $x$ is a good number.
- 3 a b x — for $i\in[a,b]$ increase $t_{i}$ by $x$. After this repeat the process while at least one $t_{i}$ is bad.
You can note that after each query all $t_{i}$ are good.
|
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 tree for each index $i\in[1,n]$ let's keep the distance to the next power of 42. After each "add on the interval" we should find the minimum and check if it's positive. If not then we should change value of the closest power of $42$ for this index, and change the value in the tree. Then, we should again find the minimum in the tree, and so on. The amortized complexity is $O((n + q) * log(n) * log_{42}(values))$. It can be proved that numbers won't exceed $(n + q) * 1e9 * log$. Now let's think about the remaining operation of changing all interval to some value. We can set only one number (the last one) to the given value, and set other values to INF. We want to guarantee that if $t[i] \neq t[i + 1]$ then the $i$-th value is correctly represented in the tree. Otherwise, it can be INF instead (or sometimes it may be correctly represented, it doesn't bother me). When we have the old query of type "add something to interval $[a, b]$" then if index $a - 1$ or index $b$ contains INF in the tree then we should first retrieve the true value there. You can see that each operation changes $O(1)$ values from INF to something finite. So, the amortized complexity is still $O((n + q) * log(n) * log_{42}(values)$. One thing regarding implementation. In my solution there is "$set < int > interesting$" containing indices with INF value. I think it's easier to implemement the solution with this set.
|
[
"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 potenga(int v)
{
for (int i=1; 1; i<<=1)
{
if (i>=v)
{
return i;
}
}
}
inline long long wie(long long v)
{
return poty[lower_bound(poty.begin(), poty.end(), v)-poty.begin()];
}
inline long long brak(long long v)
{
return wie(v)-v;
}
inline void pusz(int v)
{
if (v>=n1)
{
czybom[v]=1;
bom[v]+=narz[v];
narz[v]=0;
maxd[v]=bom[v];
mind[v]=bom[v];
zos[v]=brak(bom[v]);
return;
}
int cel1, cel2;
cel1=(v<<1);
cel2=(cel1^1);
if (czybom[v])
{
czybom[cel1]=1;
bom[cel1]=bom[v];
narz[cel1]=0;
czybom[cel2]=1;
bom[cel2]=bom[v];
narz[cel2]=0;
czybom[v]=0;
bom[v]=0;
}
narz[cel1]+=narz[v];
narz[cel2]+=narz[v];
narz[v]=0;
mind[v]=inf;
maxd[v]=-inf;
zos[v]=inf;
for (int h=0; h<2; h++)
{
if (czybom[cel1])
{
bom[cel1]+=narz[cel1];
narz[cel1]=0;
maxd[v]=max(maxd[v], bom[cel1]);
mind[v]=min(mind[v], bom[cel1]);
zos[v]=min(zos[v], brak(bom[cel1]));
}
else
{
maxd[v]=max(maxd[v], maxd[cel1]+narz[cel1]);
mind[v]=min(mind[v], mind[cel1]+narz[cel1]);
zos[v]=min(zos[v], zos[cel1]-narz[cel1]);
}
swap(cel1, cel2);
}
}
void dod(int v, int a, int b, int graa, int grab, long long w)
{
if (a>=graa && b<=grab)
{
narz[v]+=w;
return;
}
if (a>grab || b<graa)
{
return;
}
pusz(v);
dod((v<<1), a, (a+b)>>1, graa, grab, w);
dod((v<<1)^1, (a+b+2)>>1, b, graa, grab, w);
pusz(v);
}
void zmi(int v, int a, int b, int graa, int grab, long long w)
{
if (a>=graa && b<=grab)
{
narz[v]=0;
czybom[v]=1;
bom[v]=w;
return;
}
if (a>grab || b<graa)
{
return;
}
pusz(v);
zmi((v<<1), a, (a+b)>>1, graa, grab, w);
zmi((v<<1)^1, (a+b+2)>>1, b, graa, grab, w);
pusz(v);
}
void popr(int v)
{
pusz(v);
if (zos[v]>=0)
{
return;
}
if (mind[v]==maxd[v])
{
czybom[v]=1;
bom[v]=mind[v];
narz[v]=0;
pusz(v);
return;
}
popr((v<<1));
popr((v<<1)^1);
pusz(v);
}
long long wyn;
void czyt(int v, int a, int b, int cel)
{
if (a>cel || b<cel)
return;
pusz(v);
if (a==b)
{
wyn=bom[v];
return;
}
czyt((v<<1), a, (a+b)>>1, cel);
czyt((v<<1)^1, (a+b+2)>>1, b, cel);
}
int main()
{
scanf("%d%d", &n, &q);
n1=potenga(n+2);
poty.push_back(1);
for (int i=1; i<=11; i++)
poty.push_back(poty.back()*42);
zmi(1, 1, n1, 1, n1, 0);
for (int i=1; i<=n; i++)
{
scanf("%d", &p1);
zmi(1, 1, n1, i, i, p1);
}
while(q--)
{
scanf("%d", &typ);
if (typ==1)
{
scanf("%d", &p1);
czyt(1, 1, n1, p1);
printf("%lldn", wyn);
}
if (typ==2)
{
scanf("%d%d%d", &p1, &p2, &p3);
zmi(1, 1, n1, p1, p2, p3);
}
if (typ==3)
{
scanf("%d%d%d", &p1, &p2, &p3);
dod(1, 1, n1, p1, p2, p3);
while(1)
{
popr(1);
if (zos[1]==0)
{
dod(1, 1, n1, p1, p2, p3);
}
else
{
break;
}
}
}
}
return 0;
}
|
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 cards with the same number. Of course, he won't discard cards if it's impossible to choose two or three cards with the same number.
Given five numbers written on cards, cay you find the minimum sum of numbers on remaining cards?
|
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 = max(best_remove, 3 * t[i]);
}
printf("%dn", t[0]+t[1]+t[2]+t[3]+t[4]-best_remove);
return 0;
}
|
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 knows that there is \textbf{at most one} criminal in each city.
Limak is going to use a BCD (Bear Criminal Detector). The BCD will tell Limak how many criminals there are for every distance from a city $a$. After that, Limak can catch a criminal in each city for which he \textbf{is sure} that there must be a criminal.
You know in which cities criminals are. Count the number of criminals Limak will catch, after he uses the BCD.
|
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]) {
// i and j have the same distance to a
// also, there is a criminal in exactly one of them
impossible[i] = impossible[j] = true;
}
int answer = 0;
for(int i = 1; i <= n; ++i)
if(t[i] == 1 && !impossible[i])
++answer;
printf("%dn", answer);
return 0;
}
|
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 of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.
Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?
|
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 good = true;\n break;\n }\n }\n\n if (good) {\n cout << \"YES\";\n } else {\n cout << \"NO\";\n }\n\n return 0;\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 that he have bought only some houses (for $1 234 567$ game-coins each), cars (for $123 456$ game-coins each) and computers (for $1 234$ game-coins each).
Kolya is now interested, whether he could have spent all of his initial $n$ game-coins buying only houses, cars and computers or there is a bug in the game. Formally, is there a triple of non-negative integers $a$, $b$ and $c$ such that $a × 1 234 567 + b × 123 456 + c × 1 234 = n$?
Please help Kolya answer this question.
|
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 }\n cout << \"NO\";\n\n return 0;\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 several integers (possibly none), some of them might be equal.
In order to better learn this data structure Petya took an empty heap and applied some operations above to it. Also, he carefully wrote down all the operations and their results to his event log, following the format:
- insert $x$ — put the element with value $x$ in the heap;
- getMin $x$ — the value of the minimum element contained in the heap was equal to $x$;
- removeMin — the minimum element was extracted from the heap (only one instance, if there were many).
All the operations were correct, i.e. there was at least one element in the heap each time getMin or removeMin operations were applied.
While Petya was away for a lunch, his little brother Vova came to the room, took away some of the pages from Petya's log and used them to make paper boats.
Now Vova is worried, if he made Petya's sequence of operations inconsistent. For example, if one apply operations one-by-one in the order they are written in the event log, results of getMin operations might differ from the results recorded by Petya, and some of getMin or removeMin operations may be incorrect, as the heap is empty at the moment they are applied.
Now Vova wants to add some new operation records to the event log in order to make the resulting sequence of operations correct. That is, the result of each getMin operation is equal to the result in the record, and the heap is non-empty when getMin ad removeMin are applied. Vova wants to complete this as fast as possible, as the Petya may get back at any moment. He asks you to add the least possible number of operation records to the current log. Note that arbitrary number of operations may be added at the beginning, between any two other operations, or at the end of the log.
|
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$, where $x$ can be any number, and then apply $removeMin$ If current operation is $getMin$ $x$ then do follows: While heap is not empty and its minimal element is less than $x$, apply operation $removeMin$. Now if heap is empty or its minimal element is not equal to $x$, apply operation $insert$ $x$. Apply operation $getMin$ $x$. In order to fit time limit, you need to use data structure, which allows you to apply given operations in $O(logN)$ time, where $N$ is a number of elements in it. For example, std::priority_queue or std::multiset.
|
[
"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 vector<pair<string, int> > ans;\n priority_queue<int> q;\n\n for (int i = 0; i < n; i++) {\n string s;\n cin >> s;\n if (s == INSERT) {\n int x;\n cin >> x;\n q.push(-x);\n ans.push_back(make_pair(s, x));\n } else if (s == GET) {\n int x;\n cin >> x;\n while (!q.empty() && -q.top() < x) {\n q.pop();\n ans.push_back(make_pair(REMOVE, NO_X));\n }\n if (q.empty() || -q.top() > x) {\n q.push(-x);\n ans.push_back(make_pair(INSERT, x));\n }\n ans.push_back(make_pair(s, x));\n } else { // s == REMOVE\n if (q.empty()) {\n ans.push_back(make_pair(INSERT, 0));\n } else {\n q.pop();\n }\n ans.push_back(make_pair(s, NO_X));\n }\n }\n\n cout << ans.size() << \"\\n\";\n for (auto& p : ans) {\n cout << p.first;\n if (p.second != NO_X) {\n cout << \" \" << p.second;\n }\n cout << \"\\n\";\n }\n\n\n return 0;\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 considered to be the ancestor of the man number $B$ if at least one of the following conditions is satisfied:
- $A = B$;
- the man number $A$ is the father of the man number $B$;
- there is a man number $C$, such that the man number $A$ is his ancestor and the man number $C$ is the father of the man number $B$.
Of course, if the man number $A$ is an ancestor of the man number $B$ and $A ≠ B$, then the man number $B$ is not an ancestor of the man number $A$.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.
- A list of candidates is prepared, containing some (possibly all) of the $n$ men in some order.
- Each of the $n$ men decides to give a gift.
- In order to choose a person to give a gift to, man $A$ looks through the list and picks the first man $B$ in the list, such that $B$ is an ancestor of $A$ and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.
- If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the $n$ men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
|
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 need to build such sequence of vertex, that for every vertex $i$ the leftmost vertex in the sequence which is ancestor of $i$ must be equal to $a_{i}$. Or you need to tell, that such sequence does not exists. Solution: Assume sequence $ans$, which contains every vertex from sequence $a_{n}$ by once and only them. Let's order elements of this sequence in such way, that for every $i$ and $j$ if $ans_{i}$ - ancestor of $ans_{j}$, then $i \ge j$. If this sequecne is the answer, then print it. Otherwise, there is no answer. Why? If some vertex $a_{i}$ from sequence $a$ in not present in $ans$, then a man, who needs to give a gift to a man number $a_{i}$, will not be able to do it. So every vertex $a_{i}$ must have place in the resulting sequence. If $a_{i}$ - ancestor of $a_{j}$ and $i < j$, then a man, who needs to give a gift to a man number $a_{j}$ will not be able to do it. How can we build this sequence? Let's sort vertices topologically, than reverse it and remove redundant vertices. Now we need to check if that this sequence can be the answer. Let's calculate to whom every man will give his gift. At start for any man we don't know that. Let's iterate through vertices of the resulting sequence. For every vertex (man) from current vertex subtree (i.e. for vertices whose ancestor is current vertex) such that we still don't know whom will this vertex (man) give a gift to, stays that these vertices would give a gift to current vertex, because it is their first ancestor in the list. Iterate through that vertices (men) in dfs order and remember for them, to whom they will give their gift. After we apply this operation to all vertices from resulting sequence, compare for each man to whom he will give his gift and to whom he needs to give his gift. If there is at least one mismatch, then the answer doesn't exist.
|
[
"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; i < g[v].size(); i++) {\n dfs1(g[v][i]);\n }\n ts.push_back(v);\n}\n\nint r[MAX_N];\nvoid dfs2(int v, int x) {\n if (r[v] != -1) {\n return;\n }\n r[v] = x;\n for (int i = 0; i < g[v].size(); i++) {\n dfs2(g[v][i], x);\n }\n}\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n int n, m;\n cin >> n >> m;\n for (int i = 0; i < m; i++) {\n int x, y;\n cin >> x >> y;\n --x;\n --y;\n g[x].push_back(y);\n }\n\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n --a[i];\n inA[a[i]] = true;\n }\n\n for (int i = 0; i < n; i++) {\n if (!used[i]) {\n dfs1(i);\n }\n }\n\n memset(r, -1, sizeof(r));\n vector<int> ans;\n for (int i = 0; i < n; i++) {\n if (inA[ts[i]]) {\n dfs2(ts[i], ts[i]);\n ans.push_back(ts[i]);\n }\n }\n\n for (int i = 0; i < n; i++) {\n if (r[i] != a[i]) {\n cout << -1;\n return 0;\n }\n }\n\n\n cout << ans.size() << \"\\n\";\n for (int i = 0; i < ans.size(); i++) {\n cout << ans[i] + 1 << \"\\n\";\n }\n\n\n return 0;\n}"
|
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 plates standing on the table, in $T$ seconds. Shadow casted by any of the plates has the shape of a circle. Shadow circles may intersect, nest or overlap arbitrarily.
The cockroach uses the following strategy: first he equiprobably picks a direction to run towards and then runs towards it with the constant speed $v$. If at some moment $t ≤ T$ it reaches any shadow circle, it immediately stops in the shadow and thus will stay alive. Otherwise the cockroach is killed by the Dima's precise strike. Consider that the Dima's precise strike is instant.
Determine the probability of that the cockroach will stay alive.
|
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 t$. Let's iterate through all the shadow circles and figure out how each circle relates to "cockroach circle". We want to find the maximum angle, such that choosing the direction from this angle the cockroach will have enough time to reach current circle and survive. In general, maximal "surviving" angle, such that choosing the direction from it the cockroach will reach the circle in infinite time - is an angle between two tangents from a start point to the circle. If length of this tangents is not greater than $v \times t$, then this angle is the needed one. Otherwise we need to find intersections of cockroach circle and current circle. If there is no intersection points or there is only one, then current circle is too far away from cockroach. Otherwise intersection points and start point form the needed angle for this circle. After we've found all the angles, we can figure out that those angles are segments that cover a segment from $0$ to $2 \pi $. Sort their ends and find a length of their union. This length divided by $2 \pi $ will give us the answer.
|
[
"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 return sqrt(sqrDist(x1, y1, x2, y2));\n}\n\nconst double PI = acos(-1.0);\n\nint main() {\n int x0, y0, v, t;\n\n scanf(\"%d%d%d%d\", &x0, &y0, &v, &t);\n\n double r0 = 1.0 * v * t;\n\n int n;\n scanf(\"%d\", &n);\n\n vector<pair<double, int> > a;\n\n for (int i = 0; i < n; i++) {\n int x, y, r;\n scanf(\"%d%d%d\", &x, &y, &r);\n double d = sqrDist(x, y, x0, y0);\n if (d < 1.0 * r * r + eps) {\n printf(\"%.11f\", 1.0);\n return 0;\n }\n d = sqrt(d);\n if (r + r0 < d - eps) {\n continue;\n }\n\n double angL, angR, ang;\n double angM = atan2(y - y0, x - x0);\n if (angM < 0) {\n angM += 2 * PI;\n }\n\n double tLen = sqrt(d * d - 1.0 * r * r);\n if (tLen < r0 + eps) {\n ang = asin(r / d);\n } else {\n ang = acos((d * d + r0 * r0 - 1.0 * r * r) / (2 * d * r0));\n }\n\n angL = angM - ang;\n angR = angM + ang;\n\n if (angL < 0) {\n a.push_back(make_pair(angL + 2 * PI, 1));\n a.push_back(make_pair(2 * PI, -1));\n a.push_back(make_pair(0.0, 1));\n a.push_back(make_pair(angR, -1));\n } else if (angR > 2 * PI) {\n a.push_back(make_pair(angL, 1));\n a.push_back(make_pair(2 * PI, -1));\n a.push_back(make_pair(0.0, 1));\n a.push_back(make_pair(angR - 2 * PI, -1));\n } else {\n a.push_back(make_pair(angL, 1));\n a.push_back(make_pair(angR, -1));\n }\n }\n\n sort(a.begin(), a.end());\n\n double last = 0;\n int c = 0;\n double ans = 0;\n\n for (auto& p : a) {\n if (c > 0) {\n ans += p.first - last;\n }\n c += p.second;\n last = p.first;\n }\n\n ans /= 2 * PI;\n printf(\"%.11f\", ans);\n\n return 0;\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 first column and the other from the second column, such that their sum is divisible by $5$.
Formally, Alyona wants to count the number of pairs of integers $(x, y)$ such that $1 ≤ x ≤ n$, $1 ≤ y ≤ m$ and $(x+y)\mod5$ equals $0$.
As usual, Alyona has some troubles and asks you to help.
|
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, she may not apply any operation to the array at all.
Formally, after applying some operations Alyona will get an array of $n$ positive integers $b_{1}, b_{2}, ..., b_{n}$ such that $1 ≤ b_{i} ≤ a_{i}$ for every $1 ≤ i ≤ n$. Your task is to determine the maximum possible value of mex of this array.
Mex of an array in this problem is the \textbf{minimum positive} integer that doesn't appear in this array. For example, mex of the array containing $1$, $3$ and $4$ is equal to $2$, while mex of the array containing $2$, $3$ and $2$ is equal to $1$.
|
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 vertex $v$ sad if there is a vertex $u$ in subtree of vertex $v$ such that $dist(v, u) > a_{u}$, where $a_{u}$ is the number written on vertex $u$, $dist(v, u)$ is the sum of the numbers written on the edges on the path from $v$ to $u$.
Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.
Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?
|
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, v)$ in dfs, where $v$ is ancestor of $u$ (vertex, in which we now stand). And if the difference between the $dist(1, u)$ and that minimum is greater than $a_{u}$, then remove $a_{u}$ with the whole subtree.
|
[
"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 because she is too small, $k$ does not exceed $10$. The girl wants now to choose $k$ disjoint non-empty substrings of string $s$ such that these strings appear as disjoint substrings of string $t$ and in the same order as they do in string $s$. She is also interested in that their length is maximum possible among all variants.
Formally, Alyona wants to find a sequence of $k$ non-empty strings $p_{1}, p_{2}, p_{3}, ..., p_{k}$ satisfying following conditions:
- $s$ can be represented as concatenation $a_{1}p_{1}a_{2}p_{2}... a_{k}p_{k}a_{k + 1}$, where $a_{1}, a_{2}, ..., a_{k + 1}$ is a sequence of arbitrary strings (some of them may be possibly empty);
- $t$ can be represented as concatenation $b_{1}p_{1}b_{2}p_{2}... b_{k}p_{k}b_{k + 1}$, where $b_{1}, b_{2}, ..., b_{k + 1}$ is a sequence of arbitrary strings (some of them may be possibly empty);
- sum of the lengths of strings in sequence is maximum possible.
Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence.
A substring of a string is a subsequence of consecutive characters of the string.
|
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$ otherwise. When the state is d[i][j][cnt][end], you can add the following letters in the string s or t, though it will not be included in the response subsequence. Then d[i + 1][j][cnt][0] = max(d[i + 1][j][cnt][0], d[i][j][cnt][end]), d[i][j + 1][cnt][0] = max(d[i][j + 1][cnt][0], d[i][j][cnt][end]). So the new value of end is 0, because the new letter is not included in the response subsequence. If s[i] = t[j], then if $end = 1$, we can update the d[i + 1][j + 1][k][1] = max(d[i][j][k][end] + 1, d[i + 1][j + 1][k][1]). When we add an element to the response subsequence, the number of substring, which it is composed, will remain the same, because $end = 1$. If $end = 0$, we can update d[i + 1][j + 1][k + 1][1] = max(d[i][j][k][end] + 1, d[i + 1][j + 1][k + 1][1]). In this case, the new characters, which we try to add to the response subsequence, will form a new substring, so in this case we do the transition from the state $k$ to the state $k + 1$. The answer will be the largest number among the states of the d[n][m][k][end], where the values of $k$ and $end$ take all possible values.
|
[
"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, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from $n$ given points.
|
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 not greater than $4S$, and it contains all the points of the set. Let us assume that there is a point lying outside the triangle-response. Then we can get longer height to some side of triangle, so we have chosen a triangle with not maximum area(contradiction).
|
[
"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 day in $n$ hours, and each hour in $m$ minutes. Personal watches of each robber are divided in two parts: first of them has the smallest possible number of places that is necessary to display any integer from $0$ to $n - 1$, while the second has the smallest possible number of places that is necessary to display any integer from $0$ to $m - 1$. Finally, if some value of hours or minutes can be displayed using less number of places in base $7$ than this watches have, the required number of zeroes is added at the beginning of notation.
Note that to display number $0$ section of the watches is required to have at least one place.
Little robber wants to know the number of moments of time (particular values of hours and minutes), such that all digits displayed on the watches are \textbf{distinct}. Help her calculate this number.
|
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 cases. Depending on the implementation it will be $O(BASE BASE^{BASE})$, $O(BASE^{BASE})$ or $O(BASE BASE!)$, where $BASE = 7$. Actually the most simple implementation is just to cycle between all posible hour:minute combinations and check them. In the worst case, it will work in $O(BASE BASE^{BASE})$.
|
[
"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):
if minute:
return 1
else:
return gen(0, True)
else:
ans = 0
for digit in range(BASE):
if not used[digit] and (smaller or digit <= max_val[pos]):
used[digit] = True
ans += gen(pos + 1, minute, smaller or digit < max_val[pos])
used[digit] = False
return ans
n, m = map(int, input().split())
n -= 1
m -= 1
used = [False] * BASE
max_hour = itov(n)
max_minute = itov(m)
print(gen())
|
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 interested in the structure of this tree.
After doing some research he formed $q$ queries he is interested in. The $i$-th query asks to find a centroid of the subtree of the node $v_{i}$. Your goal is to answer all queries.
Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node $v$ is formed by nodes $u$, such that node $v$ is present on the path from $u$ to root.
Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
|
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 the vertex with the smallest subtree size satisfying the constraint above. Let's prove, that this vertex is centroid indeed. If it isn't, then after cutting some part will have subtree size greater than $\textstyle{\frac{1}{2}}$ of subtree size of query vertex. It isn't upper part (because of constraint above), it is one of our sons. Ouch, it's subtree less than of selected vertex, and it's still greater than $\textstyle{\frac{1}{2}}$ of subtree size of query vertex. Contradiction. So we find a centroid. We write the euler tour of tree and we will use a 2D segment tree in order to search for a vertex quickly. Complexity $O(n\log n+q\log^{2}n)$ You can consider all answers by one in dfs using this idea. Use std::set for pair (subtree size, vertex number) and at each vertex merge sets obtained from children. (Also known as "merging sets" idea) Thus we get the answers for all vertex and we need only output answers for queries. Complexity $O(n\log^{2}n+q)$ Solution by ch_egor: Solve it for all subtrees. We can solve the problem for some subtree, after solving the problem for all of it's children. Let's choose the heaviest child. Note that the centroid of the child after a certain lifting goes into our centroid. Let's model the lifting. Thus we get the answers for all vertex and we need only output answers for queries. Complexity $O(n + q)$
|
[
"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(linker, "/STACK:256000000")
using namespace std;
typedef long long int int64;
typedef long double double80;
const int INF = (1 << 29) + 5;
const int64 LLINF = (1ll << 59) + 5;
const int MOD = 1000 * 1000 * 1000 + 7;
const int MAX_N = 300 * 1000 + 5;
const int MAX_Q = 300 * 1000 + 5;
int n, q;
vector<int> graph[MAX_N];
int size_of[MAX_N];
int prev_of[MAX_N];
int big_subtree[MAX_N];
int centroid[MAX_N];
bool is_centroid_of_subtree(int v, int c)
{
return ((size_of[v] - size_of[c]) * 2 <= size_of[v] && big_subtree[c] * 2 <= size_of[v]);
}
void dfs_calc(int v, int p)
{
big_subtree[v] = 0;
size_of[v] = 1;
prev_of[v] = p;
for (int i = 0; i < graph[v].size(); ++i)
{
dfs_calc(graph[v][i], v);
size_of[v] += size_of[graph[v][i]];
big_subtree[v] = max(big_subtree[v], size_of[graph[v][i]]);
}
}
void dfs_centroid(int v)
{
if (size_of[v] == 1)
{
centroid[v] = v;
}
else
{
int ptr = 0;
for (int i = 0; i < graph[v].size(); ++i)
{
dfs_centroid(graph[v][i]);
if (size_of[graph[v][ptr]] < size_of[graph[v][i]])
{
ptr = i;
}
}
int c = centroid[graph[v][ptr]];
while (!is_centroid_of_subtree(v, c))
{
c = prev_of[c];
}
centroid[v] = c;
}
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
scanf("%d %d", &n, &q);
int v;
for (int i = 0; i < n - 1; ++i)
{
scanf("%d", &v);
graph[v - 1].push_back(i + 1);
}
dfs_calc(0, 0);
dfs_centroid(0);
for (int i = 0; i < q; ++i)
{
scanf("%d", &v);
printf("%d\n", centroid[v - 1] + 1);
}
fclose(stdin);
fclose(stdout);
return 0;
}
|
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 blind, but this mole was granted as special vision by the Old Lady. He can watch any underground objects on any distance, even through the obstacles and other objects. However, the quality of the picture depends on the Manhattan distance to object being observed.
Mole wants to find an optimal point to watch roses, that is such point with \textbf{integer coordinates} that the maximum Manhattan distance to the rose is minimum possible.
As usual, he asks you to help.
Manhattan distance between points $(x_{1}, y_{1}, z_{1})$ and $(x_{2}, y_{2}, z_{2})$ is defined as $|x_{1} - x_{2}| + |y_{1} - y_{2}| + |z_{1} - z_{2}|$.
|
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 and check for solution. This area can be decsribed by following inequalities: (You can achieve them if you expand modules in inequality "manhattan distance <= const") $.. \le x + y + z \le ..$ $.. \le - x + y + z \le ..$ $.. \le x - y + z \le ..$ $.. \le x + y - z \le ..$ $..$ denote some constants. If you intersect set of such system, you will get system of the same form, so let's learn how to solve such system. Let's replace some variables: $a = - x + y + z$ $b = x - y + z$ $c = x + y - z$ Then: $x + y + z = a + b + c$ $x = (b + c) / 2$ $y = (a + c) / 2$ $z = (a + b) / 2$ Now the system transforms into: $.. \le a \le ..$ $.. \le b \le ..$ $.. \le c \le ..$ $.. \le a + b + c \le ..$ We need to check if the system has solution in integers, also the numbers $a$, $b$, $c$ must be of the same parity (have equal remainder after division by $2$). (This is required for $x$, $y$, $z$ to be integers too) Let's get rid of parity constraint. Bruteforce the parity of $a$, $b$, $c$ (two cases) Make following replacement: $a = 2a' + r$, $b = 2b' + r$, $c = 2c' + r$, where $r = 0$ or $r = 1$. Substitute in equations above, simplify, and gain the same system for $a'$, $b'$, $c'$ without parity constraint. And now the system can be solved greedy (At first set $a$, $b$, $c$ with minimum, and then raise slowly if necessary). Total complexity is $O(n\log v)$.
|
[
"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 WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; If not, see <http://www.gnu.org/licenses/>.
#include <iostream>
#include <vector>
#include <stdint.h>
#include <algorithm>
#include <set>
#include <map>
#include <array>
#include <queue>
#include <stack>
#include <functional>
#include <utility>
#include <string>
#include <assert.h>
#include <iterator>
using std::cin;
using std::cout;
using std::cerr;
using std::vector;
using std::map;
using std::array;
using std::set;
using std::string;
using std::pair;
using std::make_pair;
using std::min;
using std::abs;
using std::max;
using std::sort;
using std::generate;
using std::min_element;
using std::max_element;
template <typename T>
T input() {
T res;
cin >> res;
return res;
}
struct coord {
int64_t x;
int64_t y;
int64_t z;
};
struct equation {
pair<int64_t, int64_t> S;
pair<int64_t, int64_t> a;
pair<int64_t, int64_t> b;
pair<int64_t, int64_t> c;
};
vector<coord> list;
equation operator+(const equation& e1, const equation& e2) {
equation res;
res.S = {max(e1.S.first, e2.S.first), min(e1.S.second, e2.S.second)};
res.a = {max(e1.a.first, e2.a.first), min(e1.a.second, e2.a.second)};
res.b = {max(e1.b.first, e2.b.first), min(e1.b.second, e2.b.second)};
res.c = {max(e1.c.first, e2.c.first), min(e1.c.second, e2.c.second)};
return res;
}
coord get_solution(const equation& eq) {
if ((eq.S.first > eq.S.second)
or (eq.a.first > eq.a.second)
or (eq.b.first > eq.b.second)
or (eq.c.first > eq.c.second))
return coord {INT64_MAX, INT64_MAX, INT64_MAX};
if ((eq.a.first + eq.b.first + eq.c.first > eq.S.second)
or (eq.a.second + eq.b.second + eq.c.second < eq.S.first))
return coord {INT64_MAX, INT64_MAX, INT64_MAX};
coord res;
res.x = eq.a.first;
res.y = eq.b.first;
res.z = eq.c.first;
int64_t delta = max(int64_t(0), eq.S.first - res.x - res.y - res.z);
res.x += min(delta, eq.a.second - eq.a.first);
delta -= min(delta, eq.a.second - eq.a.first);
res.y += min(delta, eq.b.second - eq.b.first);
delta -= min(delta, eq.b.second - eq.b.first);
res.z += min(delta, eq.c.second - eq.c.first);
delta -= min(delta, eq.c.second - eq.c.first);
assert(delta == 0);
return res;
}
int64_t DIV2(int64_t arg) {
return (arg - (arg & 1)) / 2;
}
coord can(int64_t MAXANS) {
equation eq;
eq.S = eq.a = eq.b = eq.c = {INT64_MIN, INT64_MAX};
for (const coord& crd: list) {
equation nw;
nw.S = { crd.x + crd.y + crd.z - MAXANS, crd.x + crd.y + crd.z + MAXANS};
nw.a = {-crd.x + crd.y + crd.z - MAXANS, -crd.x + crd.y + crd.z + MAXANS};
nw.b = { crd.x - crd.y + crd.z - MAXANS, crd.x - crd.y + crd.z + MAXANS};
nw.c = { crd.x + crd.y - crd.z - MAXANS, crd.x + crd.y - crd.z + MAXANS};
eq = eq + nw;
}
for (int64_t r = 0; r <= 1; ++r) {
equation tr = eq;
tr.S.first = DIV2(tr.S.first - 3 * r + 1);
tr.a.first = DIV2(tr.a.first - r + 1);
tr.b.first = DIV2(tr.b.first - r + 1);
tr.c.first = DIV2(tr.c.first - r + 1);
tr.S.second = DIV2(tr.S.second - 3 * r);
tr.a.second = DIV2(tr.a.second - r);
tr.b.second = DIV2(tr.b.second - r);
tr.c.second = DIV2(tr.c.second - r);
coord sol = get_solution(tr);
if (sol.x != INT64_MAX) {
coord ans;
ans.x = r + sol.y + sol.z;
ans.y = r + sol.x + sol.z;
ans.z = r + sol.x + sol.y;
return ans;
}
}
return coord {INT64_MAX, INT64_MAX, INT64_MAX};
}
int main() {
std::iostream::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
list.reserve(100000);
for (size_t T = input<size_t>(); T != 0; --T) {
list.resize(input<size_t>());
for (coord& crd: list)
cin >> crd.x >> crd.y >> crd.z;
int64_t L = -1; // definitely imposible
int64_t R = 3 * int64_t(1000 * 1000 * 1000) * int64_t(1000 * 1000 * 1000) + 10; // definitely possible
while (R - L > 1) {
int64_t M = L + (R - L) / 2;
if (can(M).x != INT64_MAX)
R = M;
else
L = M;
}
coord ans = can(R);
cout << ans.x << " " << ans.y << " " << ans.z << "\n";
}
return 0;
}
|
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 spread over the field, each piece occupying exactly one cell and no two pieces occupying the same cell. To estimate the difficulty of the task Kay looks at some squares of size $k × k$ cells, with corners located at the corners of the cells and sides parallel to coordinate axis and counts the number of pieces of the ice inside them.
This method gives an estimation of the difficulty of some part of the field. However, Kay also wants to estimate the total difficulty, so he came up with the following criteria: for each $x$ ($1 ≤ x ≤ n$) he wants to count the number of squares of size $k × k$, such that there are exactly $x$ pieces of the ice inside.
Please, help Kay estimate the difficulty of the task given by the Snow Queen.
|
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 some of the shaded points is not very large, namely - if the point has coordinates $(x, y)$, then the set of left bottom corners of square is defined as ${(a, b)|x - k + 1 < = a < = x, y - k + 1 < = b < = y}$. Let's consider each point $(x, y)$ as the $2$ events: Add one to the all elements with indexes from $y - k + 1$ to $y$ on the row $x - k + 1$ and take one at the same interval on the row $x + 1$. How to calculate answer? Suppose we update the value of a cell on the row $a$, and before it was updated the value $x$ on the row $b$. Let add to the answer for the number of squares containing $x$ points value $a - b$. We can implement the addition of the segment directly and have $O(nk)$ for processing all the events that fit in time limit. To get rid of $O(MAXCORD)$ memory, we need to write all interested in the coordinates before processing events (them no more than nk) and reduce the coordinates in the events. It takes $O(n\log(n k))$ time and $O(nk)$ memory. Now we can execute the previous point in $O(nk)$ memory. Complexity is $O(n\log(n k)+n k)$ time and $O(nk)$ memory.
|
[
"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(linker, "/STACK:256000000")
using namespace std;
typedef long long int int64;
typedef long double double80;
const int INF = (1 << 29) + 5;
const int64 LLINF = (1ll << 59) + 5;
const int MOD = 1000 * 1000 * 1000 + 7;
const int MAX_N = 1000 * 100 + 5;
const int MAX_K = 305;
/** Interface */
inline int readChar();
template <class T = int> inline T readInt();
template <class T> inline void writeInt(T x);
inline void writeChar(int x);
inline void writeWord(const char *s);
inline void flush();
/** Read */
static const int buf_size = 20 * 1000 * 1000;
inline int getChar()
{
static char buf[buf_size];
static int len = 0, pos = 0;
if (pos == len)
pos = 0, len = fread(buf, 1, buf_size, stdin);
if (pos == len)
return -1;
return buf[pos++];
}
inline int readChar()
{
int c = getChar();
while (c <= 32)
c = getChar();
return c;
}
template <class T>
inline T readInt()
{
int s = 1, c = readChar();
T x = 0;
if (c == '-')
s = -1, c = getChar();
while ('0' <= c && c <= '9')
x = x * 10 + c - '0', c = getChar();
return s == 1 ? x : -x;
}
inline int64 readInt64()
{
int s = 1, c = readChar();
int64 x = 0;
if (c == '-')
s = -1, c = getChar();
while ('0' <= c && c <= '9')
x = x * 10 + c - '0', c = getChar();
return s == 1 ? x : -x;
}
/** Write */
static int write_pos = 0;
static char write_buf[buf_size];
inline void writeChar(int x)
{
if (write_pos == buf_size)
fwrite(write_buf, 1, buf_size, stdout), write_pos = 0;
write_buf[write_pos++] = x;
}
inline void flush()
{
if (write_pos)
fwrite(write_buf, 1, write_pos, stdout), write_pos = 0;
}
template <class T>
inline void writeInt(T x)
{
if (x < 0)
writeChar('-'), x = -x;
char s[24];
int n = 0;
while (x || !n)
s[n++] = '0' + x % 10, x /= 10;
while (n--)
writeChar(s[n]);
}
inline void writeInt64(int64 x)
{
if (x < 0)
writeChar('-'), x = -x;
char s[24];
int n = 0;
while (x || !n)
s[n++] = '0' + x % 10, x /= 10;
while (n--)
writeChar(s[n]);
}
inline void writeWord(const char *s)
{
while (*s)
writeChar(*s++);
}
struct point
{
int x;
int y;
};
struct ask
{
int l;
int r;
int ptr;
int type;
};
bool cmp(const ask &a, const ask &b)
{
return a.ptr < b.ptr;
}
int n, k;
point arr[MAX_N];
int cord[MAX_N * 2];
ask asks[MAX_N * 2];
int cord_len = 0;
int asks_len = 0;
bool have_prev_cord[MAX_N * 2];
bool have_prev_line[MAX_N * 2];
int last_of_cord[MAX_N * 2];
int last_of_line[MAX_N * 2];
int at_cord[MAX_N * 2];
int at_line[MAX_N * 2];
int64 answer[MAX_N];
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
n = readInt();
k = readInt();
for (int i = 0; i < n; ++i)
{
arr[i].x = readInt();
arr[i].y = readInt();
cord[cord_len++] = arr[i].x;
cord[cord_len++] = arr[i].x - k + 1;
}
sort(cord, cord + 2 * n);
cord_len = unique(cord, cord + 2 * n) - cord;
for (int i = 0; i < n; ++i)
{
asks[asks_len].l = lower_bound(cord, cord + cord_len, arr[i].x - k + 1) - cord;
asks[asks_len].r = lower_bound(cord, cord + cord_len, arr[i].x) - cord;
asks[asks_len].ptr = arr[i].y - k + 1;
asks[asks_len].type = 1;
++asks_len;
asks[asks_len].l = asks[asks_len - 1].l;
asks[asks_len].r = asks[asks_len - 1].r;
asks[asks_len].ptr = arr[i].y + 1;
asks[asks_len].type = -1;
++asks_len;
}
sort(asks, asks + asks_len, cmp);
memset(answer, 0, sizeof(answer));
memset(last_of_cord, 0, sizeof(last_of_cord));
memset(last_of_line, 0, sizeof(last_of_line));
memset(at_cord, 0, sizeof(at_cord));
memset(at_line, 0, sizeof(at_line));
memset(have_prev_cord, 0, sizeof(have_prev_cord));
memset(have_prev_line, 0, sizeof(have_prev_cord));
for (int i = 0; i < asks_len; ++i)
{
for (int j = asks[i].l; j <= asks[i].r; ++j)
{
if (!have_prev_cord[j])
{
have_prev_cord[j] = true;
last_of_cord[j] = asks[i].ptr;
at_cord[j] += asks[i].type;
}
else
{
answer[at_cord[j]] += asks[i].ptr - last_of_cord[j];
last_of_cord[j] = asks[i].ptr;
at_cord[j] += asks[i].type;
}
if (j != asks[i].r)
{
if (!have_prev_line[j])
{
have_prev_line[j] = true;
last_of_line[j] = asks[i].ptr;
at_line[j] += asks[i].type;
}
else
{
answer[at_line[j]] += 1ll * (cord[j + 1] - cord[j] - 1) * (asks[i].ptr - last_of_line[j]);
last_of_line[j] = asks[i].ptr;
at_line[j] += asks[i].type;
}
}
}
}
for (int i = 1; i <= n; ++i)
{
writeInt64(answer[i]);
writeChar(' ');
}
flush();
fclose(stdin);
fclose(stdout);
return 0;
}
|
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 equal to $i$, she will leave the road exactly at the moment $i$. In case she steps on the road $i$ at the moment of time greater than $i$, she stays there forever.
Gerda starts at the moment of time $l$ at the intersection number $s$ and goes to the palace of the Snow Queen, located at the intersection number $t$. Moreover, she has to be there at the moment $r$ (or earlier), before the arrival of the Queen.
Given the description of the road network, determine for $q$ queries $l_{i}$, $r_{i}$, $s_{i}$ and $t_{i}$ if it's possible for Gerda to get to the palace on time.
|
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 consider it's location relative to centre of edges array. If it's stricly on the left half or on the right half, then solve recursively (You need to implement function like $solve(requests, l, r)$). How to answer on query, if it contains the centre? Let's precalculate two dp's: $dp_{r}[i] =$ bitset of vertices you can from to the $v_{i}$ or $u_{i}$ with $l = m$ and $r = i$. $dp_{l}[i] =$ bitset of vertices you can go to starting from $v_{i}$ or $u_{i}$ with $l = i$ and $r = m - 1$ $v_{i}$ and $u_{i}$ are vertices of i'th edge. Using this dp the answer is yes if and ony if $dp_{l}[l][u] = true$ and $dp_{r}[r][u] = true$ for some $u$. All above can be implemented using bitwise operations. So the time is $O({\frac{n m\log m}{32}})$
|
[
"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 WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; If not, see <http://www.gnu.org/licenses/>.
#include <iostream>
#include <vector>
#include <stdint.h>
#include <algorithm>
#include <set>
#include <map>
#include <array>
#include <queue>
#include <stack>
#include <functional>
#include <utility>
#include <string>
#include <assert.h>
#include <iterator>
#include <bitset>
using std::cin;
using std::cout;
using std::cerr;
using std::vector;
using std::map;
using std::array;
using std::set;
using std::string;
using std::pair;
using std::make_pair;
using std::min;
using std::abs;
using std::max;
using std::sort;
using std::generate;
using std::min_element;
using std::max_element;
#define size_t uint32_t
struct Req {
size_t L;
size_t R;
size_t S;
size_t T;
size_t ID;
};
struct Edge {
size_t v;
size_t u;
size_t prev1;
size_t prev2;
size_t next1;
size_t next2;
};
const size_t MAXQ = 200000;
const size_t MAXN = 1000;
const size_t MAXM = 200000;
char answers[MAXQ];
Edge list[MAXM];
vector<size_t> last[MAXN];
std::bitset<MAXN> masks_r[MAXM / 2 + 10];
std::bitset<MAXN> masks_l[MAXM / 2 + 10];
void solve_layer(vector<Req>& requests, size_t l, size_t m, size_t r) {
bool has = false;
for (size_t i = 0; i != requests.size(); ++i)
has or_eq (requests[i].L <= m - 1 and requests[i].R >= m);
if (not has)
return;
for (size_t i = 0; i != r - m; ++i) {
masks_r[i] = std::bitset<MAXN>();
if (list[m + i].prev1 >= m and list[m + i].prev1 != std::numeric_limits<size_t>::max())
masks_r[i] |= masks_r[list[m + i].prev1 - m];
if (list[m + i].prev2 >= m and list[m + i].prev2 != std::numeric_limits<size_t>::max())
masks_r[i] |= masks_r[list[m + i].prev2 - m];
masks_r[i][list[m + i].v] = true;
masks_r[i][list[m + i].u] = true;
}
for (size_t z = 0; z != m - l; ++z) {
size_t i = (m - l) - 1 - z;
masks_l[i] = std::bitset<MAXN>();
if (list[l + i].next1 < m)
masks_l[i] |= masks_l[list[l + i].next1 - l];
if (list[l + i].next2 < m)
masks_l[i] |= masks_l[list[l + i].next2 - l];
masks_l[i][list[l + i].v] = true;
masks_l[i][list[l + i].u] = true;
}
for (size_t i = 0; i != requests.size();)
if (requests[i].L <= m - 1 and requests[i].R >= m) {
answers[requests[i].ID] = (masks_r[requests[i].R - m] & masks_l[requests[i].L - l]).any();
std::swap(requests[i], requests.back());
requests.pop_back();
} else {
++i;
}
}
void solve(vector<Req>& requests, size_t l, size_t r) {
if (l == r - 1) {
for (auto& req: requests)
answers[req.ID] = (req.S == list[l].v or req.S == list[l].u)
and (req.T == list[l].v or req.T == list[l].u);
return;
}
size_t m = l + (r - l) / 2;
// [l, m), [m, r).
solve_layer(requests, l, m, r);
vector<Req> right;
for (size_t i = 0; i != requests.size();)
if (requests[i].L >= m) {
right.push_back(requests[i]);
std::swap(requests[i], requests.back());
requests.pop_back();
} else {
++i;
}
requests.shrink_to_fit();
solve(requests, l, m);
solve(right, m, r);
}
int main() {
size_t n, m, q;
scanf("%d %d %d", &n, &m, &q);
assert(n <= MAXN);
assert(q <= MAXQ);
assert(m <= MAXM);
std::fill(answers, answers + q, 16);
for (size_t i = 0; i != m; ++i) {
scanf("%d %d", &list[i].v, &list[i].u);
--list[i].v, --list[i].u;
list[i].prev1 = list[i].prev2 = list[i].next1 = list[i].next2 = std::numeric_limits<size_t>::max();
if (not last[list[i].v].empty()) {
list[i].prev1 = last[list[i].v].back();
if (list[last[list[i].v].back()].v == list[i].v)
list[last[list[i].v].back()].next1 = i;
else {
list[last[list[i].v].back()].next2 = i;
}
}
if (not last[list[i].u].empty()) {
list[i].prev2 = last[list[i].u].back();
if (list[last[list[i].u].back()].v == list[i].u)
list[last[list[i].u].back()].next1 = i;
else {
list[last[list[i].u].back()].next2 = i;
}
}
last[list[i].v].push_back(i);
last[list[i].u].push_back(i);
}
vector<Req> requests;
for (size_t i = 0; i != q; ++i) {
Req req;
scanf("%d %d %d %d", &req.L, &req.R, &req.S, &req.T);
--req.L, --req.R, --req.S, --req.T;
req.ID = i;
auto it1 = std::lower_bound(last[req.S].begin(), last[req.S].end(), req.L);
auto it2 = std::upper_bound(last[req.T].begin(), last[req.T].end(), req.R);
if (it1 == last[req.S].end() or it2 == last[req.T].begin())
answers[i] = false;
else {
req.L = *it1;
req.R = *std::prev(it2);
if (req.L > req.R)
answers[i] = false;
else
requests.push_back(req);
}
}
solve(requests, 0, m);
for (size_t i = 0; i != q; ++i) {
printf("%s", (answers[i] ? "Yes\n" : "No\n"));
}
return 0;
}
|
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 queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).
If a carrier with $d$ ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take $d$ ice cream packs comes to the house, then Kay and Gerda will give him $d$ packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.
Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
|
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:
sad += 1
sys.stdout.write(str(answer) + " " + str(sad))
main()
|
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 repeatedly names numbers $l$ and $r$ such that $r - l + 1$ is even. After that animals that occupy positions between $l$ and $r$ inclusively are rearranged as follows: the animal at position $l$ swaps places with the animal at position $l + 1$, the animal $l + 2$ swaps with the animal $l + 3$, ..., finally, the animal at position $r - 1$ swaps with the animal $r$.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most $20 000$ segments, since otherwise the robber girl will become bored and will start scaring the animals again.
|
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 to do $20 000$ actions, therefore, we can write any quadratic sort, which changes the neighboring elements in each iteration (bubble sort for example). Complexity $O(n^{2})$
|
[
"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 this set, i.e. $u\in A$ or $v\in A$ (or both).
Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.
They have agreed to give you their graph and you need to find two \textbf{disjoint} subsets of its vertices $A$ and $B$, such that both $A$ and $B$ are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).
|
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 to be bipartite. And being bipartite is also sufficient, you can use each part as a vertex cover. Bipartition can be found using your favorite graph traversing algorithm(BFS or DFS). Here is a tutorial for bipartition of undirected graphs. The complexity is $O(n + m)$.
|
[
"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_back(v);
for(int u : g[v])
{
if(!mark[u] && dfs(u, 3 - color))
return 1;
if(mark[u] != 3 - color)
return 1;
}
return 0;
}
int main()
{
int n, m;
cin >> n >> m;
for(int i = 0; i < m; i++)
{
int u = in() - 1;
int v = in() - 1;
g[u].push_back(v);
g[v].push_back(u);
}
for(int i = 0; i < n; i++)
if(!mark[i])
{
if(g[i].empty())
continue;
if(dfs(i))
{
cout << -1 << endl;
return 0;
}
}
for(int i = 0; i < 2; i++)
{
cout << vc[i].size() << endl;
for(int v : vc[i])
cout << v + 1 << " ";
cout << endl;
}
}
|
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 $k$ and the ancient values, tell us if Arya has a winning strategy independent of value of $x$ or not. Formally, is it true that Arya can understand the value $x\ {\mathrm{mod}}\ k$ for any positive integer $x$?
Note, that $x\ {\mathrm{mod}}\ y$ means the remainder of $x$ after dividing it by $y$.
|
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. We have $x_{1} - x_{2} \equiv 0$ (${\mathrm{mod~}}c_{i}$) for each $1 \le i \le n$. So: $l c m(c_{1},c_{2},\ldots,c_{n})\mid x_{1}-x_{2}$ We also have $x_{1}-x_{2}\neq0$ ($\mathrm{mod}\,k$). As a result: $k\mid l c m(c_{1},c_{2},\ldots,c_{n})$ We've found a necessary condition. And I have to tell you it's also sufficient! Assume $k\mid l c m(c_{1},c_{2},\ldots,c_{n})$, we are going to prove there exists $x_{1}, x_{2}$ such that $x_{1} - x_{2} \equiv 0$ (${\mathrm{mod~}}c_{i}$) (for each $1 \le i \le n$), and $x_{1}-x_{2}\neq0$ ($\mathrm{mod}\,k$). A possible solution is $x_{1} = lcm(c_{1}, c_{2}, ..., c_{n})$ and $x_{2} = 2 \times lcm(c_{1}, c_{2}, ..., c_{n})$, so the sufficiency is also proved. So you have to check if $lcm(c_{1}, c_{2}, ..., c_{n})$ is divisible by $k$, which could be done using prime factorization of $k$ and $c_{i}$ values. For each integer $x$ smaller than $MAXC$, find it's greatest prime divisor $gpd_{x}$ using sieve of Eratosthenes in $O(M A X C\log M A X C)$. Then using $gpd$ array, you can write the value of each coin as $p_{1}^{q1}p_{2}^{q2}...p_{m}^{qm}$ where $p_{i}$ is a prime integer and $1 \le q_{i}$ holds. This could be done in $O(\log c_{i})$ by moving from $c_{i}$ to $\frac{c!}{p!d_{c}}$ and adding $gpd_{ci}$ to the answer. And you can factorize $k$ by the same way. Now for every prime $p$ that $p\mid k$, see if there exists any coin $i$ that the power of $p$ in the factorization of $c_{i}$ is not smaller than the power of $p$ in the factorization of $k$. Complexity is $O((M A X C+n)\log M A X C)$.
|
[
"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] = i;
int n = in(), k = in();
for(int i = 0; i < n; i++)
{
int x = in();
while(x > 1)
{
int p = isP[x];
int cnt = 0;
while(x % p == 0)
{
cnt++;
x /= p;
}
cntP[p] = max(cntP[p], cnt);
}
}
bool ok = 1;
while(k > 1)
{
ok &= (cntP[isP[k]] > 0);
cntP[isP[k]]--;
k /= isP[k];
}
cout << (ok ? "Yes\n" : "No\n");
}
|
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 values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values $x$, such that Arya will be able to make $x$ using some subset of coins with the sum $k$.
Formally, Pari wants to know the values $x$ such that there exists a subset of coins with the sum $k$ such that some subset of this subset has the sum $x$, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum $x$ using these coins.
|
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 this subset. The $i$-th coin is used in both subsets. So $dp_{i, j, k}$ is equal to $dp_{i - 1, j, k} OR dp_{i - 1, j - ci, k} OR dp_{i - 1, j - ci, k - ci}$. The complexity is $O(nk^{2})$.
|
[
"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 last = 1 - now;
int x = in();
for(int j = 0; j <= k; j++)
for(int y = 0; y <= j; y++)
{
dp[now][j][y] = dp[last][j][y];
if(j >= x)
{
dp[now][j][y] |= dp[last][j - x][y];
if(y >= x)
dp[now][j][y] |= dp[last][j - x][y - x];
}
}
}
vector <int> res;
for(int i = 0; i <= k; i++)
if(dp[n % 2][k][i])
res.push_back(i);
cout << res.size() << endl;
for(int x : res)
cout << x << " ";
cout << endl;
}
|
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 between these cities, numbered from $1$ to $m$. The $i$-th road had length equal to $w_{i}$. The Great Arya and Pari The Great were discussing about destructing some prefix (all road with numbers less than some $x$) and suffix (all roads with numbers greater than some $x$) of the roads so there will remain only the roads with numbers $l, l + 1, ..., r - 1$ and $r$.
After that they will divide the great kingdom into two pieces (with each city belonging to exactly one piece) such that the hardness of the division is \textbf{minimized}. The hardness of a division is the \textbf{maximum length} of a road such that its both endpoints are in the same piece of the kingdom. In case there is no such road, the hardness of the division is considered to be equal to $ - 1$.
Historians found the map of the great kingdom, and they have $q$ guesses about the $l$ and $r$ chosen by those great rulers. Given these data, for each guess $l_{i}$ and $r_{i}$ print the minimum possible hardness of the division of the kingdom.
|
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 answer of the query. Use this idea to optimize your solution. First, let's solve a single query separately. Sort edges from interval [l, r] in decreasing order of weights. Using dsu, we can find longest prefix of these edges, which doesn't contains odd cycle. (Graph will be bipartite after adding these edges.) The answer will be weight of the next edge. (We call this edge "bottleneck"). Why it's correct? Because if the answer is $w$, then the we can divide the graph in a way that none of the edges in the same part have value greater than $w$. So the graph induced by the edges with value greater than $w$ must be bipartite. And if this graph is bipartite, then we can divide the graph into two parts as the bipartition, so no edge with value greater than $w$ will be in the same part, and the answer is at most $w$. Let's have a look at this algorithm in more details. For each vertex, we keep two values in dsu: Its parent and if its part differs from its parent or not. We keep the second value equal to "parity of length of the path in original graph, between this node and its parent". We can divide the graph anytime into two parts, walking from one vertex to its parent and after reaching the root, see if the starting vertex must be in the same part as the root or not. In every connected component, there must not exist any edge with endpoints in the same part. After sorting the edges, there are 3 possible situations for an edge when we are adding it to the graph: The endpoints of this edge are between two different components of the current graph. Now we must merge these two components, and update the part of the root of one of the components. The endpoints of this edge are in the same component of the current graph, and they are in different parts of this component. There is nothing to do. The endpoints of this edge are in the same component of the current graph, and they are also in the same part of this component. This edge is the "bottleneck" and we can't keep our graph bipartite after adding it, so we terminate the algorithm. We call the edges of the first and the third type "valuable edges". The key observation is: If we run above algorithm on the valuable edges, the answer remains the same. Proof idea: The edges of the first type are spanning trees of connected components of the graph, and with a spanning tree of a bipartite graph, we can uniquely determine if two vertices are in the same part or not. So if we can ignore all other edges and run our algorithm on these valuable edges, we have $O(n)$ edges instead of original $O(n^{2})$ and the answer is the same. We answer the queries using a segment tree on the edges. In each node of this tree, we run the above algorithm and memorize the valuable edges. By implementing carefully (described here), making the segment tree could be done in $O(m\log m\alpha(n))$. Now for each query $[l, r]$, you can decompose $[l, r]$ into $O(\log n)$ segments in segment tree and each one has $O(n)$ valuable edges. Running the naive algorithm on these edges lead to an $O(n\log n)$ solution for each query, which fits in time limit.
|
[
"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), u(u), w(w) { }
bool operator <(const Edge &e) const { return w < e.w; }
};
struct Segment
{
int l, r;
Segment(int l = 0, int r = 0): l(l), r(r) { }
};
typedef vector <Edge> Edges;
int n, m, q;
Edge es[M];
Edges seg[S];
Segment range[S];
int par[N], cost[N], rank[N];
Segment merge(Segment l, Segment r) { return Segment(l.l, r.r); }
void clear(Edges &es)
{
for(Edge e : es)
{
par[e.v] = par[e.u] = -1;
cost[e.v] = cost[e.u] = 0;
rank[e.v] = rank[e.u] = 1;
}
}
int root(int v)
{
if(par[v] == -1)
return v;
int u = root(par[v]);
cost[v] ^= cost[par[v]];
return par[v] = u;
}
int parity(int v)
{
root(v);
return cost[v];
}
int merge(Edge e)
{
if(rank[root(e.u)] > rank[root(e.v)])
swap(e.u, e.v);
if(root(e.u) == root(e.v))
{
if(parity(e.u) == parity(e.v))
return 2;
return 0;
}
int u = root(e.u);
int v = root(e.v);
cost[u] ^= (parity(e.u) ^ 1 ^ parity(e.v));
par[u] = root(v);
rank[v] += rank[u];
return 1;
}
bool hasOddCycle;
Edges merge(Edges &a, Edges &b)
{
Edges c;
merge(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c));
clear(c);
Edges res;
for(int i = c.size() - 1; i >= 0; i--)
{
int x = merge(c[i]);
if(x)
res.push_back(c[i]);
if(x == 2)
{
hasOddCycle = 1;
break;
}
}
reverse(res.begin(), res.end());
return res;
}
void make()
{
for(int i = S - 1; i; i--)
{
if(i >= M)
{
range[i] = Segment(i - M, i - M + 1);
if(i - M < m)
seg[i].push_back(es[i - M]);
}
else
{
range[i] = merge(range[i * 2], range[i * 2 + 1]);
seg[i] = merge(seg[i * 2], seg[i * 2 + 1]);
}
}
}
int solve(Segment s)
{
Edges es;
hasOddCycle = 0;
for(int l = s.l + M, r = s.r + M; l < r; l /= 2, r /= 2)
{
if(l % 2)
es = merge(es, seg[l++]);
if(r % 2)
es = merge(es, seg[--r]);
}
if(hasOddCycle)
return es[0].w;
return -1;
}
int main()
{
cin >> n >> m >> q;
for(int i = 0; i < m; i++)
{
es[i].u = in() - 1;
es[i].v = in() - 1;
es[i].w = in();
}
make();
while(q--)
{
int l = in() - 1, r = in();
cout << solve(Segment(l, r)) << "\n";
}
}
|
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 disappointed. Suddenly a bright idea came to his mind!
Here is how his dirty code looks like:
\begin{verbatim}
dfs(v)
{
set count[v] = count[v] + 1
if(count[v] < 1000)
{
foreach u in neighbors[v]
{
if(visited[u] is equal to false)
{
dfs(u)
}
break
}
}
set visited[v] = true
}
main()
{
input the digraph()
TOF()
foreach 1<=i<=n
{
set count[i] = 0 , visited[i] = false
}
foreach 1 <= v <= n
{
if(visited[v] is equal to false)
{
dfs(v)
}
}
... // And do something cool and magical but we can't tell you what!
}
\end{verbatim}
He asks you to write the \underline{TOF} function in order to optimize the running time of the code with minimizing the number of calls of the \underline{dfs} function. The input is a directed graph and in the \underline{TOF} function you have to rearrange the edges of the graph in the list \underline{neighbors} for each vertex. The number of calls of \underline{dfs} function depends on the arrangement of \underline{neighbors} of each vertex.
|
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 of dfs calls equals to $998 \times ($ sum of sizes of cycles $) + n +$ number of cycles. The goal is to minimize the sum of cycle sizes. Or, to maximize the number of vertices which are not in any cycle. Name them good vertices. If there exists a vertex $v$ without any outgoing edge, we can make all of the vertices that $v$ is reachable from them good. Consider the dfs-tree from $v$ in the reverse graph. You can choose the edge $u\rightarrow p d r_{u}$ from this tree as the first edge in neighbors[u], in order to make all of these vertices good. Vertices which are not in the sink strongly connected components could become good too, by choosing the edges from a path starting from them and ending in a sink strongly connected component. In a sink strongly connected component, there exists a path from every vertex to others. So we can make every vertex good except a single cycle, by choosing the edges in the paths from other nodes to this cycle and the cycle edges. So, every vertices could become good except a single cycle in every sink strongly connected component. And the length of those cycles must be minimized, so we can choose the smallest cycle in every sink strongly connected component and make every other vertices good. Finding the smallest cycle in a graph with $n$-vertex and $m$ edges could be done in $O(n(n + m))$ with running a BFS from every vertex, so finding the smallest cycle in every sink strongly connected component is $O(n(n + m))$ overall.
|
[
"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, vector <int> &nodes)
{
mark[v] = 1;
for(int u : g[v])
if(!mark[u])
dfs(u, g, nodes);
nodes.push_back(v);
}
int findSmallestCycle(vector <int> vs)
{
vector <int> cycle;
for(int root : vs)
{
for(int v : vs)
{
bfsDist[v] = 1e9;
bfsPar[v] = -1;
}
bfsDist[root] = 0;
queue <int> q;
q.push(root);
bool cycleFound = 0;
while(q.size() && !cycleFound)
{
int v = q.front();
q.pop();
for(int u : g[v])
{
if(u == root)
{
cycleFound = 1;
int curLen = bfsDist[v];
if(cycle.empty() || curLen < cycle.size())
{
cycle.clear();
for(; v != -1; v = bfsPar[v])
cycle.push_back(v);
}
break;
}
if(bfsDist[u] > bfsDist[v] + 1)
{
bfsDist[u] = bfsDist[v] + 1;
bfsPar[u] = v;
q.push(u);
}
}
}
}
return cycle.size();
}
int main()
{
int n, m;
cin >> n >> m;
for(int i = 0; i < m; i++)
{
int u = in() - 1;
int v = in() - 1;
g[u].push_back(v);
gR[v].push_back(u);
}
vector <int> order;
for(int i = 0; i < n; i++)
if(!mark[i])
dfs(i, g, order);
fill(mark, mark + n, 0);
fill(comp, comp + n, -1);
int inCycle = 0, nCycle = 0;
for(; order.size(); order.pop_back())
{
int v = order.back();
if(mark[v])
continue;
vector <int> curComp;
dfs(v, gR, curComp);
bool isSink = true;
for(int u : curComp)
comp[u] = v;
for(int u : curComp)
for(int k = 0; k < g[u].size(); k++)
if(comp[g[u][k]] != v)
isSink = false;
if(isSink)
{
int x = findSmallestCycle(curComp);
if(x > 0)
{
nCycle++;
inCycle += x;
}
}
}
cout << 999 * inCycle + (n - inCycle) + nCycle << endl;
}
|
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 Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.
For each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of \textbf{consecutive} days that he will beat all present opponents.
Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.
|
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 finding for each element of $canWin$, the closest zero to it from left. The complexity of this solution is $O(nd)$, but the limits allow you to solve the problem in $O(nd^{2})$ by iterating over all possible subsegments and check if each one of them is full of ones or not.
|
[
"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 behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a $2$-digit $11$ or $6$-digit $122221$), so maybe she could see something in them.
Now Pari asks you to write a program that gets a huge integer $n$ from the input and tells what is the $n$-th even-length positive palindrome number?
|
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$ are two different $2k$-digit lovely numbers, then the first $k$ digits of $a$ and $b$ differ in at least one position. So $a$ is smaller than $b$ if and only if the first half of $a$ is smaller than the the first half of $b$. Another useful fact: The first half of a a lovely number can be any arbitrary positive integer. Using the above facts, it's easy to find the first half of the $n$-th lovely number - it exactly equals to integer $n$. When we know the first half of a lovely number, we can concatenate it with its reverse to restore the lovely integer. To sum up, the answer can be made by concatenating $n$ and it's reverse together. The complexity of this solution is $O(\log n)$.
|
[
"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\sqrt{2\mid3}}\\ {4}\end{array}\right|}}{\left|\begin{array}{l}{1\left|2\sqrt{3}}\\ {\left|\frac{4}{7}\displaystyle\left|8\mid9\right|}}\\ {\left|0\right|}\end{array}\right|}$
\end{center}
Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":
Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
|
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:
print("YES")
else:
print("NO")
|
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. Walking from intersection number $i$ to intersection $j$ requires $|i - j|$ units of energy. The total energy spent by Mike to visit a sequence of intersections $p_{1} = 1, p_{2}, ..., p_{k}$ is equal to $\sum_{i=1}^{k-1}|p_{i}-p_{i+1}|$ units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only $1$ unit of energy. There are exactly $n$ shortcuts in Mike's city, the $i^{th}$ of them allows walking from intersection $i$ to intersection $a_{i}$ ($i ≤ a_{i} ≤ a_{i + 1}$) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence $p_{1} = 1, p_{2}, ..., p_{k}$ then for each $1 ≤ i < k$ satisfying $p_{i + 1} = a_{pi}$ and $a_{pi} ≠ p_{i}$ Mike will spend \textbf{only $1$ unit of energy} instead of $|p_{i} - p_{i + 1}|$ walking from the intersection $p_{i}$ to intersection $p_{i + 1}$. For example, if Mike chooses a sequence $p_{1} = 1, p_{2} = a_{p1}, p_{3} = a_{p2}, ..., p_{k} = a_{pk - 1}$, he spends exactly $k - 1$ units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each $1 ≤ i ≤ n$ Mike is interested in finding minimum possible total energy of some sequence $p_{1} = 1, p_{2}, ..., p_{k} = i$.
|
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$,$j \neq i + 1$ so we can add only edges $(i, i + 1)$,$(i, i - 1)$,$(i, s[i])$ with cost 1 and then run a bfs to find the shortest path for each point $i$. You can also solve the problem by taking the best answer from left and from the right and because $a_{i} \le a_{i + 1}$ then we can just iterate for each $i$ form $1$ to $n$ and get the best answer from left and maintain a deque with best answer from right. Complexity is $O(N)$.
|
[
"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[u] = d[v] + 1
q.put(u)
u = int(a[v]) - 1
if d[u] == -1:
d[u] = d[v] + 1
q.put(u)
for i in range(0, n):
print(d[i])
|
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 one. The value of $k$ ($k > 1$) is a secret integer known only to them. It is also known that each thief's bag can carry at most $n$ chocolates (if they intend to take more, the deal is cancelled) and that there were \textbf{exactly four} thieves involved.
Sadly, only the thieves know the value of $n$, but rumours say that the numbers of ways they could have taken the chocolates (for a fixed $n$, but not fixed $k$) is $m$. Two ways are considered different if one of the thieves (they should be numbered in the order they take chocolates) took different number of chocolates in them.
Mike want to track the thieves down, so he wants to know what their bags are and value of $n$ will help him in that. Please find \textbf{the smallest possible} value of $n$ or tell him that the rumors are false and there is no such $n$.
|
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{n}}$ , so for each $k$ we can count how many $a$ satisfy the conditions $0 < a < ak < ak^{2} < ak^{3} \le n$, their number is $\left|{\frac{n}{k^{3}}}\right\rangle$. Considering this, the final answer is $\textstyle\sum_{k=2}^{\sqrt{n}}\left\lfloor{\frac{n}{k^{3}}}\right\rfloor$. Notice that this expression is non-decreasing as $n$ grows, so we can run a binary search for $n$. Total complexity: Time ~ $O(I o q(10^{16})\ast{\sqrt{M}})$, Space: $O(1)$.
|
[
"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 mid = (l+r)/2;
if (get(mid)<m) l=mid+1;
else r=mid;
}
if (get(l)==m) n=l;
cout << n << '\n';
return 0;
}
|
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 $(l, r)$, Mike can instantly tell the value of $\operatorname*{m}_{i\geq i}^{\mathsf{P a x}}a_{i}$ while !Mike can instantly tell the value of $\operatorname*{min}_{i=l}b_{i}$.
Now suppose a robot (you!) asks them all possible different queries of pairs of integers $(l, r)$ $(1 ≤ l ≤ r ≤ n)$ (so he will make exactly $n(n + 1) / 2$ queries) and counts how many times their answers coincide, thus for how many pairs $\operatorname*{m}_{i=l}^{r}a_{i}=\operatorname*{min}_{i=l}b_{i}$ is satisfied.
How many occasions will the robot count?
|
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 add $r_{max} - r_{min} + 1$ to our answer. To find the $min$ and $max$ values on a segment $[l, r]$ we can use Range-Minimum Query data structure. The complexity is $O(n\log n)$ time and $O(n\log n)$ space.
|
[
"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;
st.pop();
}
lf[i] = st.empty() ? -1 : st.top();
st.push(i);
}
}
int naive() {
int res = 0;
for (int i = 0; i < n; ++i)
for (int j = i; j < n; ++j)
if (*max_element(a + i, a + j + 1) == *min_element(b + i, b + j + 1))
res++;
return res;
}
bool read() {
if (!(cin >> n))
return false;
for (int i = 0; i < n; ++i)
assert(scanf("%d", &a[i]) == 1);
for (int i = 0; i < n; ++i)
assert(scanf("%d", &b[i]) == 1);
}
void solve() {
calc_max(a, lfa, rga);
for (int i = 0; i < n; ++i)
b[i] = -b[i];
calc_max(b, lfb, rgb);
map <int, int> pos, last;
for (int i = 0; i < n; ++i) {
b[i] = -b[i];
nxt[i] = n;
if (!pos.count(b[i]))
pos[b[i]] = i;
else
nxt[last[b[i]]] = i;
last[b[i]] = i;
}
long long res = 0;
for (int i = 0; i < n; ++i) {
if (!pos.count(a[i]))
continue;
int pb = pos[a[i]];
while (nxt[pb] <= i) {
pb = nxt[pb];
if (lfb[pb] != -1 && b[lfb[pb]] == b[pb])
lfb[pb] = lfb[lfb[pb]];
}
pos[a[i]] = pb;
for (int t = 0; t < 2 && pb < n; ++t, pb = nxt[pb]) {
int lf = max(lfa[i], lfb[pb]);
int rg = min(rga[i], rgb[pb]);
if (lf < min(i, pb) && max(i, pb) < rg)
res += (min(i, pb) - lf) * 1ll * (rg - max(i, pb));
}
}
cout << res << endl;
}
int main() {
while (read())
solve();
return 0;
}
|
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 intervals $[l_{i}, r_{i}]$ on $OX$ axis and you have to find:
\begin{center}
$\sum_{1<i_{1}<i_{2}<...<i_{k}<n}f([l_{i_{1}},r_{i_{1}}]\cap[l_{i_{2}},r_{i_{2}}]\cap...\cap\left[l_{i_{k}},r_{i_{k}}\right]).$
\end{center}
In other words, you should find the sum of the number of integer points in the intersection of any $k$ of the segments.
As the answer may be very large, output it modulo $1000000007$ ($10^{9} + 7$).
Mike can't solve this problem so he needs your help. You will help him, won't you?
|
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.Then our answer will be $\sum_{i=k}^{n}\left({}_{k}^{'}\right)*d p[i]$. We can easily calculate array $dp$ using a map and partial sum trick,here you can find about it. The complexity and memory is $O(n\log n)$ and $O(n)$.
|
[
"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 gen()
{
ll b = 1;
c[k] = 1;
for (int i=k+1; i<=n; i++)
b*= i,b%=mod,b*=pp(i-k,mod-2),b%=mod,c[i]=b;
}
ll ans = 0;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin>>n>>k;
gen();
for (int i=0; i<n; i++)
cin>>a[2*i].x>>a[2*i+1].x,a[2*i].y = 1,a[2*i+1].y=-1,a[2*i+1].x++;
sort(a,a+2*n, [] (s x, s y) { if (x.x!=y.x) return (x.x<y.x); return (x.y>y.y);});
int last = a[0].x;
int now = 0;
for (int i=0; i<2*n;)
{
int d = a[i].x;
ans += 1ll * c[now] * (d-last);
ans%=mod;
while (a[i].x==d)
now+=a[i].y,i++;
last = d;
}
cout<<ans;
return 0;
}
|
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 fastened in a right way.
|
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}
\end{center}
You are given a string $s$. Check if the string is "s-palindrome".
|
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;
}
} else if (opposite.count(s[i])) {
if ((sz(s) & 1) && i == (sz(s) >> 1)) {
puts("NIE");
return;
}
if (s[sz(s) - 1 - i] != opposite[s[i]]) {
puts("NIE");
return;
}
} else {
puts("NIE");
return;
}
}
puts("TAK");
}
|
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 written without decimal point. Also there should not be extra zeroes in $a$ and $b$.
|
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 by one). Complexity: $O(n)$.
|
[
"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 (expv > 0) expv--;
forn(t, 2) {
while (s.back() == '0') s.pop_back();
reverse(all(s));
}
if (sz(s) > 1) s.insert(1, ".");
if (expv == 0) printf("%s\n", s.c_str());
else printf("%sE%d\n", s.c_str(), expv);
}
|
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 $1, 2, ..., n$. $p$ is lexicographically smaller than the $q$ if a number $1 ≤ i ≤ n$ exists, so $p_{k} = q_{k}$ for $1 ≤ k < i$ and $p_{i} < q_{i}$.
|
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 lexicographically maximal permutation. Complexity: $O(n + m)$.
|
[
"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, pos;
void dfs(int v) {
if (used[v]) return;
used[v] = true;
pos.pb(v);
perm.pb(p[v]);
for (auto to : g[v]) dfs(to);
}
int ans[N];
void solve() {
forn(i, n) {
g[i].clear();
used[i] = false;
}
forn(i, m) {
g[a[i].x].pb(a[i].y);
g[a[i].y].pb(a[i].x);
}
int cnt = 0;
forn(i, n)
if (!used[i]) {
cnt++;
pos.clear();
perm.clear();
dfs(i);
sort(all(pos));
sort(all(perm), greater<int>());
forn(j, sz(perm))
ans[pos[j]] = perm[j];
}
forn(i, n) {
if (i) putchar(' ');
printf("%d", ans[i] + 1);
}
puts("");
}
|
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}\}$ for all $1 ≤ i ≤ k$. The symbol $\otimes$ is used for the binary exclusive or operation.
How many "xor-sequences" of length $k$ exist? Output the answer modulo $10^{9} + 7$.
\textbf{Note if $a = [1, 1]$ and $k = 1$ then the answer is $2$, because you should consider the ones from $a$ as different.}
|
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} = {z_{i - 1, j}}$ and a matrix $G = {g_{ij}}$. Easy to see that $z_{i} = G \times z_{i - 1}$. So $z_{n} = G^{n}z_{0}$. Let's use the associative property of matrix multiplication: at first let's calculate $G^{n}$ with binary matrix exponentiation and then multiply it to the vector $z_{0}$. Complexity: $O(n^{3}logk)$.
|
[
"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 int mul(int a, int b) { return int(a * 1ll * b % mod); }
int count(li x) {
int ans = 0;
while (x) {
ans++;
x &= x - 1;
}
return ans;
}
void mul(int a[N][N], int b[N][N], int n) {
static int c[N][N];
forn(i, n)
forn(j, n) {
c[i][j] = 0;
forn(k, n) inc(c[i][j], mul(a[i][k], b[k][j]));
}
forn(i, n) forn(j, n) a[i][j] = c[i][j];
}
void bin_pow(int a[N][N], li b, int n) {
static int ans[N][N];
forn(i, n) forn(j, n) ans[i][j] = i == j;
while (b) {
if (b & 1) mul(ans, a, n);
mul(a, a, n);
b >>= 1;
}
forn(i, n) forn(j, n) a[i][j] = ans[i][j];
}
void solve() {
static int a[N][N];
memset(a, 0, sizeof(a));
forn(i, n) {
forn(j, n)
a[i][j] = count(::a[i] ^ ::a[j]) % 3 == 0;
a[i][n] = 1;
}
//forn(i, n + 1) clog << mp(a[i], n + 1) << endl;
bin_pow(a, k, n + 1);
int ans = 0;
forn(i, n + 1) inc(ans, a[i][n]);
cout << ans << endl;
}
|
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 number written on this ball is the rectangle's width in meters. This ball is not returned to the bag, and the second player reaches into the bag and grabs another ball — the number written on this ball is the rectangle's height in meters. If the area of the rectangle is greater than or equal some threshold $p$ square meters, the players win. Otherwise, they lose.
The organizers of the game are trying to select an appropriate value for $p$ so that the probability of a couple winning is not too high and not too low, but they are slow at counting, so they have hired you to answer some questions for them. You are given a list of the numbers written on the balls, the organizers would like to know how many winning pairs of balls exist for different values of $p$. Note that two pairs are different if either the first or the second ball is different between the two in pair, and two different balls with the same number are considered different.
|
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 the values from $z$ we can use something like Eratosthenes sieve: let's iterate over the first multiplier $a$ and the multiple of it $b = ka$ and increment $z_{b}$ by the value $cnt_{a} \cdot cnt_{k}$. After calculating the array $z$ we should calculate the array of its partial sums and find the number of less pairs in $O(1)$ time. Complexity: $O(n + XlogX)$, where $X$ is the maximal value in $p$.
|
[
"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]]++;
fore(a, 1, N) {
if (!cnt[a]) continue;
for (int b = a; b < N; b += a) {
if (b / a != a) z[b] += li(cnt[a]) * cnt[b / a];
else z[b] += li(cnt[a]) * (cnt[a] - 1);
}
}
fore(i, 1, N) z[i] += z[i - 1];
forn(i, m) {
li ans = li(n) * (n - 1) - z[p[i] - 1];
printf("%lld\n", ans);
}
}
|
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 between any two intersections.
Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will $q$ consecutive events happen soon. There are two types of events:
1. Government makes a new rule. A rule can be denoted by integers $v$, $u$ and $w$. As the result of this action, the passing fee of all roads on the shortest path from $u$ to $v$ increases by $w$ dollars.
2. Barney starts moving from some intersection $v$ and goes to intersection $u$ where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.
Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
|
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 depth[v] < depth[u]: swap(v, u) v = v/2 // v/2 is parent of vertex v Time Complexity: $O(q l g(q)l g(M A X_{-}V))$
|
[
"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)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )
";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )
";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
unordered_map<ll, ll> mp;
inline ll lca(ll v, ll u, ll w = -1){
ll ans = 0;
while(v != u){
if(v < u) swap(v, u);
if(mp.find(v) != mp.end()) ans += mp[v];
if(~w) mp[v] += w;
v >>= 1;
}
return ans;
}
int main(){
iOS;
int q;
cin >> q;
while(q--){
int type;
ll v, u;
cin >> type >> v >> u;
if(type == 1){
ll w;
cin >> w;
lca(v, u, w);
}
else
cout << lca(v, u) << '
';
}
return 0;
}
|
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 visit any city he wants by following roads.
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
\begin{verbatim}
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
\end{verbatim}
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city $i$, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
|
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$ but not $u$ $y$ is an ancestor of $u$ but not $v$ $x$ and $y$ share the same direct parent; That is $par[x] = par[y]$. The probability that $y$ occurs sooner than $x$ in $children[par[x]]$ after shuffling is $0.5$. So the probability that $starting_time[u] < starting_time[v]$ is $0.5$. Also We know if $u$ is ancestor of $v$ this probability is $1$ and if it's in subtree of $v$ the probability is $0$. That's why answer for $v$ is equal to $\frac{n-s u b[v]-h[v]}{2}+d e p t h[v]$ ($depth$ is 1-based and $sub[v]$ is the number of vertices in subtree of $v$ including $v$ itself). Because $n - sub[v] - h[v]$ is the number of vertices like the first $u$ (not in subtree of $v$ and not an ancestor of $v$). Thus answer is always either an integer or an integer and a half. Time complexity: ${\cal O}(n)$
|
[
"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)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )
";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )
";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
//#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 1e5 + 100;
int ans[maxn];
vi adj[maxn];
int sz[maxn];
inline void DFS(int v = 0){
sz[v] = 1;
rep(u, adj[v]){
DFS(u);
sz[v] += sz[u];
}
}
inline void dfs(int v = 0, double e = 0){
e += 2;
ans[v] = e;
int s = sz[v] - 1;
rep(u, adj[v]){
double x = s - sz[u];
dfs(u, e + x);
}
}
int main(){
int n;
scanf("%d", &n);
For(i,1,n){
int p;
scanf("%d", &p);
adj[--p].pb(i);
}
DFS();
dfs();
For(i,0,n) printf("%.1f ", (double)ans[i]/2.);
puts("");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.