contest_id
stringlengths 1
4
| index
stringclasses 43
values | title
stringlengths 2
63
| statement
stringlengths 51
4.24k
| tutorial
stringlengths 19
20.4k
| tags
listlengths 0
11
| rating
int64 800
3.5k
⌀ | code
stringlengths 46
29.6k
⌀ |
|---|---|---|---|---|---|---|---|
441
|
C
|
Valera and Tubes
|
Valera has got a rectangle table consisting of $n$ rows and $m$ columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row $x$ and column $y$ by a pair of integers $(x, y)$.
Valera wants to place exactly $k$ tubes on his rectangle table. A tube is such sequence of table cells $(x_{1}, y_{1})$, $(x_{2}, y_{2})$, $...$, $(x_{r}, y_{r})$, that:
- $r ≥ 2$;
- for any integer $i$ $(1 ≤ i ≤ r - 1)$ the following equation $|x_{i} - x_{i + 1}| + |y_{i} - y_{i + 1}| = 1$ holds;
- each table cell, which belongs to the tube, must occur exactly once in the sequence.
Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:
- no pair of tubes has common cells;
- each cell of the table belongs to some tube.
Help Valera to arrange $k$ tubes on his rectangle table in a fancy manner.
|
The solution is pretty simple. First we need to make such route that visits every cell exactly one time. It is not difficult: Initially we stay in $(1, 1)$ cell. Moving from left to right, we should reach $(1, m)$ cell. Move to the next line, in $(2, m)$ cell. Moving from right to left, we should reach the most left sell of 2nd line, $(2, 1)$. Move to the next line. Repeat 1. and 2. while we have not all cells visited. After that, we can easily find the solution: you can make first $(k - 1)$ tubes length be $2$, and the last $k$ tube will consist from cells left.
|
[
"constructive algorithms",
"dfs and similar",
"implementation"
] | 1,500
|
#undef NDEBUG
#ifdef gridnevvvit
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <list>
#include <vector>
#include <string>
#include <deque>
#include <bitset>
#include <algorithm>
#include <utility>
#include <functional>
#include <limits>
#include <numeric>
#include <complex>
#include <cassert>
#include <cmath>
#include <memory.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
typedef long long li;
typedef long double ld;
typedef pair<int,int> pt;
typedef pair<ld, ld> ptd;
typedef unsigned long long uli;
#define pb push_back
#define mp make_pair
#define mset(a, val) memset(a, val, sizeof (a))
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define ft first
#define sc second
#define sz(a) int((a).size())
#define x first
#define y second
template<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }
template<typename X> inline X sqr(const X& a) { return (a * a); }
template<typename T> inline string toStr(T x) { stringstream st; st << x; string s; st >> s; return s; }
template<typename T> inline int hasBit(T mask, int b) { return (b >= 0 && (mask & (T(1) << b)) != 0) ? 1 : 0; }
template<typename X, typename T>inline ostream& operator<< (ostream& out, const pair<T, X>& p) { return out << '(' << p.ft << ", " << p.sc << ')'; }
inline int nextInt() { int x; if (scanf("%d", &x) != 1) throw; return x; }
inline li nextInt64() { li x; if (scanf("%I64d", &x) != 1) throw; return x; }
inline double nextDouble() { double x; if (scanf("%lf", &x) != 1) throw; return x; }
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define fore(i, a, b) for(int i = int(a); i <= int(b); i++)
#define ford(i, n) for(int i = int(n - 1); i >= 0; i--)
#define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
const int INF = int(1e9);
const li INF64 = li(INF) * li(INF);
const ld EPS = 1e-9;
const ld PI = ld(3.1415926535897932384626433832795);
int n, m, k;
inline bool read() {
n = nextInt();
m = nextInt();
k = nextInt();
return true;
}
inline void solve() {
if (n == 3 && m == 3 && k == 3) {
forn(it, 3) {
cout << 3;
forn(i, 3)
cout << ' ' << it + 1 << ' ' << i + 1;
puts("");
}
return;
}
vector < pt > path;
int x = 0, y = 0, dir = 1;
path.pb(mp(x + 1, y + 1));
while (true) {
y += dir;
if (y == m) dir *= -1, y = m - 1, x ++;
if (y == -1) dir *= -1, y = 0, x++;
if (x == n) break;
path.pb(mp(x + 1, y + 1));
}
forn(i, k - 1) {
printf("%d", 2);
printf(" %d %d", path[2 * i].ft, path[2 * i].sc);
printf(" %d %d\n", path[2 * i + 1].ft, path[2 * i + 1].sc);
}
printf("%d", sz(path) - 2 * (k - 1));
for(int i = 2 * (k - 1); i < sz(path); i++) {
printf(" %d %d", path[i].ft, path[i].sc);
}
puts("");
}
int main()
{
assert(read());
solve();
}
|
441
|
D
|
Valera and Swaps
|
A permutation $p$ of length $n$ is a sequence of distinct integers $p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$. A permutation is an identity permutation, if for any $i$ the following equation holds $p_{i} = i$.
A swap $(i, j)$ is the operation that swaps elements $p_{i}$ and $p_{j}$ in the permutation. Let's assume that $f(p)$ is the minimum number of swaps that you need to make the permutation $p$ an identity permutation.
Valera wonders, how he can transform permutation $p$ into any permutation $q$, such that $f(q) = m$, using the minimum number of swaps. Help him do that.
|
In this task you should represent permutation as graph with $n$ vertexes, and from every vertex $i$ exists exactly one edge to vertex $p[i]$. It's easy to understand that such graph consists of simple cycles only. If we make swap $(i, j)$, edges $i\rightarrow p[i]$ and $j\to p[j]$ will become edges $i\rightarrow p[j]$ and $j\to p[i]$ respectively. Then if $i$ and $j$ is in the same cycle, this cycle will break: but if they are in different cycles, these cycles will merge into one: this means that every swap operation increases number of cycles by one, or decreases it by one. Assuming all above, to get permutation $q$ from permutation $p$, we need to increase (or decrease) number of cycles in $p$ to $n - m$. Let $c$ - number of cycles in $p$. Then $k$ always equals $|(n - m) - c|$. For satisfying lexicographical minimality we will review three cases: 1) $n - m < c$ It's easy to understand, that in this case you must decrease cycles number by merging cycles one by one with cycle containing vertex 1. This way every swap has form $(1, v)$, where $v > 1$. Because every cycle vertex is bigger than previous cycle vertex, this case can be solved with $O(n)$. 2) $n - m > c$ In this case you should break cycle for every vertex, making swap with smallest possible vertex (it should be in this cycle too). This could be done if represent cycle by line $p[i]\to p[p[i]]\to\dots\to i$. As soon as every cycle is broken with linear asymptotics, this case solution works with $O(n^{2})$. Bonus: this way of representing cycle lets us optimize solution to $O(n\log n)$ asymptotics, you may think how. 3) $n - m = c$ Besause in this case $k = 0$, there is nothing need to be swapped.
|
[
"constructive algorithms",
"dsu",
"graphs",
"implementation",
"math",
"string suffix structures"
] | 2,100
|
#include <cstdio>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
const int N = 3005;
int n, m, k, p[N];
bool used[N];
inline void use_cycle(int v) {
for (int i = v; !used[i]; i = p[i])
used[i] = true;
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &p[i]);
p[i]--;
}
scanf("%d", &m);
m = n - m;
for (int i = 0; i < n; ++i)
if (!used[i]) {
k++;
use_cycle(i);
}
for (int i = 0; i < n; ++i)
used[i] = false;
printf("%d\n", (int)abs(k-m));
if (k > m) {
use_cycle(0);
for (int i = 1; i < n && k > m; ++i) {
if (!used[i]) {
printf("%d %d ", 1, i+1);
k--;
use_cycle(i);
}
}
}
if (k < m) {
for (int i = 0; i < n && k < m; ++i) {
vector <int> pos(n, -1);
int cur = 0;
for (int j = p[i]; j != i; j = p[j])
pos[j] = cur++;
pos[i] = cur;
cur = 0;
for (int j = i+1; j < n && k < m; ++j)
if (pos[j] >= cur) {
printf("%d %d ", i+1, j+1);
k++;
cur = pos[j]+1;
swap(p[i], p[j]);
}
}
}
return 0;
}
|
441
|
E
|
Valera and Number
|
Valera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below:
\begin{verbatim}
//input: integers x, k, p
a = x;
for(step = 1; step <= k; step = step + 1){
rnd = [random integer from 1 to 100];
if(rnd <= p)
a = a * 2;
else
a = a + 1;
}
s = 0;
while(remainder after dividing a by 2 equals 0){
a = a / 2;
s = s + 1;
}
\end{verbatim}
Now Valera wonders: given the values $x$, $k$ and $p$, what is the expected value of the resulting number $s$?
|
We will solve the task by calculating dynamic $d[i][mask][last][cnt]$ - possibility of getting $v$ which $8$ last bits equals $mask$, 9th bit equals $last$, $cnt$ - number of consecutive bits (following 9th bit) and equal to $last$, after $i$ steps. Good, but why we left other bits? It's clear, that using operation $+ = 1$ we can change only first 0 bit with index $ \ge 9$. Transitions is pretty obvious: we add 1 or multiply by 2 (it's recommended to see them in jury's solution). Perhaps, you should ask following question. For example, we have number $x = 1011111111$ in binary representation. And at this moment, we make $+ = 1$. According to all above, we must go to $d[1][0][1][2]$ condition, but we can't do that because we don't have any information about $1$ in 10th position. But, as we can not change any bit with index $ \ge 9$ ($mask = 0$) we make transition to $d[1][0][1][1]$.
|
[
"bitmasks",
"dp",
"math",
"probabilities"
] | 2,400
|
#undef NDEBUG
#ifdef gridnevvvit
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <list>
#include <vector>
#include <string>
#include <deque>
#include <bitset>
#include <algorithm>
#include <utility>
#include <functional>
#include <limits>
#include <numeric>
#include <complex>
#include <cassert>
#include <cmath>
#include <memory.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
typedef long long li;
typedef long double ld;
typedef pair<int,int> pt;
typedef pair<ld, ld> ptd;
typedef unsigned long long uli;
#define pb push_back
#define mp make_pair
#define mset(a, val) memset(a, val, sizeof (a))
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define ft first
#define sc second
#define sz(a) int((a).size())
#define x first
#define y second
template<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }
template<typename X> inline X sqr(const X& a) { return (a * a); }
template<typename T> inline string toStr(T x) { stringstream st; st << x; string s; st >> s; return s; }
template<typename T> inline int hasBit(T mask, int b) { return (b >= 0 && (mask & (T(1) << b)) != 0) ? 1 : 0; }
template<typename X, typename T>inline ostream& operator<< (ostream& out, const pair<T, X>& p) { return out << '(' << p.ft << ", " << p.sc << ')'; }
inline int nextInt() { int x; if (scanf("%d", &x) != 1) throw; return x; }
inline li nextInt64() { li x; if (scanf("%I64d", &x) != 1) throw; return x; }
inline double nextDouble() { double x; if (scanf("%lf", &x) != 1) throw; return x; }
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define fore(i, a, b) for(int i = int(a); i <= int(b); i++)
#define ford(i, n) for(int i = int(n - 1); i >= 0; i--)
#define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
const int INF = int(1e9);
const li INF64 = li(INF) * li(INF);
const ld EPS = 1e-9;
const ld PI = ld(3.1415926535897932384626433832795);
li x;
int k;
int pl;
const int N = 402;
const int MAGIC = 9;
ld d[2][(1 << MAGIC)][2][N];
inline bool read() {
return (cin >> x >> k >> pl);
}
inline void solve() {
ld p = ld(pl) / 100;
int SPMASK = (1 << MAGIC) - 1;
li pmask = x & li(SPMASK);
li plast = (x & li(1 << MAGIC)) > 0;
li pcnt = 0;
x >>= MAGIC;
if (x == 0)
pcnt = 200;
else {
while (true) {
int bit = x & 1ll;
if (bit == plast)
pcnt++;
else
break;
x >>= 1;
}
}
d[0][pmask][plast][pcnt] = 1.0;
forn(it, k) {
int i = it & 1;
int nxt = i ^ 1;
forn(mask, (1 << MAGIC)) {
forn(last, 2) {
forn(cnt, N) {
d[nxt][mask][last][cnt] = 0.0;
}
}
}
forn(mask, (1 << MAGIC)) {
forn(last, 2) {
forn(cnt, N) {
ld dv = d[i][mask][last][cnt];
//doubling
{
int nmask = (mask << 1) & SPMASK;
int nlast = (mask & (1 << (MAGIC - 1))) > 0;
int ncnt = cnt;
if (last == nlast)
ncnt++;
else
ncnt = 1;
d[nxt][nmask][nlast][ncnt] += dv * p;
}
//adding
{
int nmask = mask + 1;
if (nmask != (1 << MAGIC)) {
d[nxt][nmask][last][cnt] += dv * (1.0 - p);
} else {
if (last == 1)
d[nxt][0][0][cnt] += dv * (1.0 - p);
else
d[nxt][0][1][1] += dv * (1.0 - p);
}
}
}
}
}
}
ld answer = 0;
k = k & 1;
forn(nmask, (1 << MAGIC)){
forn(last, 2) {
forn(cnt, N) {
int counter = 0;
int mask = nmask;
if (mask != 0) {
while (mask % 2 == 0)
counter += 1, mask /= 2;
} else {
counter = MAGIC;
if (last == 0)
counter += cnt;
}
ld dv = d[k][nmask][last][cnt];
answer += ld(counter) * ld(d[k][nmask][last][cnt]);
}
}
}
cout << fixed << setprecision(13) << answer << endl;
}
int main()
{
#ifdef gridnevvvit
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
#endif
srand(time(NULL));
cout << setprecision(10) << fixed;
cerr << setprecision(5) << fixed;
assert(read());
solve();
#ifdef gridnevvvit
cerr << "===Time: " << clock() << "===" << endl;
#endif
}
|
442
|
A
|
Borya and Hanabi
|
Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.
Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding $n$ cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has).
The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints.
A color hint goes like that: a player names some color and points at all the cards of this color.
Similarly goes the value hint. A player names some value and points at all the cards that contain the value.
Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value.
|
It's obvious that the order of hints doesn't metter. There are 10 types of hints, so we can try all $2^{10}$ vartiants of what other players should do. Now we need to check if Boris can describe all of his cards. He can do it iff he can distinguish all pairs of different cards. He can do it if somebody told at least one distinction. It can be a hint about color of one of cards (if they don't have same one) or it can be hint about value of some card.
|
[
"bitmasks",
"brute force",
"implementation"
] | 1,700
| null |
442
|
B
|
Andrey and Problem
|
Andrey needs one more problem to conduct a programming contest. He has $n$ friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.
Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.
|
Let's sort all friends in such a way that $p_{i} \le p_{j}$ iff $i \le j$. If there is $p_{i} = 1$ Andrey should ask only this friend. Now we can assume that all probabilities are less then 1. What should we maximize? ${\textstyle\sum_{i=0}^{n-1}p_{i}\prod_{j\neq i}(1-p_{j})=\sum_{i=0}^{n-1}{\textstyle{\frac{p_{i}}{1-p_{i}}}}\prod(1-p_{j})=\prod(1-p_{i})\cdot\sum{\frac{p_{i}}{1-p_{i}}}$ Let $P=\prod(1-p_{i})$, $S=\textstyle\sum{\frac{p_{i}}{1-p_{i}}}$. Assume we already have some group of people we would ask a help. Let's look what will happen with the probability of success if we add a friend with probability $p_{i}$ to this group: $\Delta=-P\cdot S+P(1-p_{i})\cdot(S+{\textstyle\frac{p_{i}}{1-p_{i}}})=P\cdot p_{i}(1-S)$ It means adding a new people to group will increase a probability of success only if $S < 1$. Now let's look at another question. We have some group of people with $S < 1$. And we want to add only one friend to this group. Which one is better? Let the probability of the first friend is $p_{i}$ and the second friend is $p_{j}$. It's better to add first one if $ \Delta _{i} - \Delta _{j} = P \cdot p_{i} \cdot (1 - S) - P \cdot p_{j} \cdot (1 - S) = P \cdot (1 - S) \cdot (p_{i} - p_{j}) > 0$. As $S < 1$ we get $p_{i} > p_{j}$. But it's only a local criteria of optimality. But, we can prove that globally you should use only a group of people with the biggest probabilities. We can use proof by contradiction. Let's look at the optimal answer with biggest used suffix (in the begining of editorial we sort all friends). Of all such answers we use one with minimum number of people in it. Where are two friends $i$ and $j$ ($p_{i}$ < $p_{j}$) and $i$-th friend is in answer and $j$-th isn't. Let's look at the answer if we exclude $i$-th friend. It should be smaller because we used optimal answer with minimum numer of people in it. So adding a new people to this group will increase success probability. But we know that adding $j$-th is better than $i$-th. So we have found a better answer. So we have a very easy solution of this problem. After sorting probabilities we should you some suffix of it. Because of sorting time complexity is $O(nlogn)$.
|
[
"greedy",
"math",
"probabilities"
] | 1,800
| null |
442
|
C
|
Artem and Array
|
Artem has an array of $n$ positive integers. Artem decided to play with it. The game consists of $n$ moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets $min(a, b)$ points, where $a$ and $b$ are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.
After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.
|
It's obvious that we should never delete the first and last elements of array. Let's look at the minimum number. Let it be $x$ and there are $n$ elements in the array. We can subtract $x$ from all elements and the answer for the problem will decrease on $(n - 2) \cdot x$, becouse we will do $n - 2$ delitions of middle elements and each of this delitions will not give Artem exectly $x$ more points. If minimal element was the first or the last one, we can not to count it now (it equals to 0 now, so it will not affect the answer now). If it locates in the middle of array, we can prove that there is exist an optimal solution when Artem deletes this element on first move. We can prove it by contradaction. Let's look at the optimal answer where the minimal element is deleted on the minimal possible move (but not on first one). We can prove that we can delete it earlier. If move which is exactly before deleting minimum uses element of array which isn't a neighbour of minimual one we can swap this two delitions and it will not affect the answer. If those elements are neighbours we can write down the number of points which we obtain in both cases and understand that to delete minimum first is the best choice. So, in this task we need to maintain a set of all not deleted elements and to find a smallest alive element. All of it we can do with built-in data structures in time $O(nlogn)$.
|
[
"data structures",
"greedy"
] | 2,500
| null |
442
|
D
|
Adam and Tree
|
When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions:
- There is no vertex that has more than two incident edges painted the same color.
- For any two vertexes that have incident edges painted the same color (say, $c$), the path between them consists of the edges of the color $c$.
Not all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree.
Initially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree.
|
First, let's solve the task with already built tree. We can do it with easy dymanic programming. We will count the answer for subtree with an edge to the parent. If we can count it for all vertices we can calculate the answer for the whole tree as maximum of answers for children of root. How to calculate it for one vertex? Suppose we already know answers for children of this vertex. We should color the edge to the parent in the same color as edge to the child with maximum answer. Let two maximum answers for child be $max_{1}$ and $max_{2}$ then the answer for this vertex would be $max(max_{1}, max_{2} + 1)$ if $max_{1} \ge max_{2}$. What changes when we can add new vertices? Nothing. We can calculate the value of dynamic programming for new vertex (it always would be 1) and recalculate value for its parent. If it doesn't change we should stop this process, in another case we continue recalculations of dynamic programming values: go to its parent and recalculate answer for it and so on. If we maintain two maximums for each vertex in $O(1)$ the asymptotic of the algorithm would be $O(nlogn)$. To prove it we can use some facts about Heavy-light decomposion. We can use the way Heavy-light decomposion splits edges of tree as our decomposition. We know that answer for such decomposition will be less than logarithm of the number of vertices. So each value of dynamic programming will be increased not more than $O(logn)$ times.
|
[
"data structures",
"trees"
] | 2,600
| null |
442
|
E
|
Gena and Second Distance
|
Gena doesn't like geometry, so he asks you to solve this problem for him.
A rectangle with sides parallel to coordinate axes contains $n$ dots. Let's consider some point of the plane. Let's count the distances from this point to the given $n$ points. Let's sort these numbers in the non-decreasing order. We'll call the beauty of the point the second element of this array. If there are two mimimum elements in this array, the beaty will be equal to this minimum.
Find the maximum beauty of a point inside the given rectangle.
|
To solve this problem we can use a binary search. How do we check that answer if not less than $R$? It means that we can draw a circle with such radius which center locates in the rectangle and there are no more than one point inside this circle. How could we check it? We always can shift this circle in such a way that at least one point would be on its border. We can try all points as one which is on border. Than we should draw a circle with center in it and intersect it with $n - 1$ circles built on other points. If there is a point on this circle which is covered with no more than one other circle, than answer is greater or equal $R$. Finding such point is almost a typical problem which can be solved in $O(klogk)$ where $k$ - number of intersections points of circles. We described a solution which works in $O(logAnswer \cdot n^{2} \cdot logn)$. But we can make it faster. Let's try all vertices as centers of circles and inside this loop make a binary search. We can make one optimize: if we can't find a point on circle with radius which is equal to the best now known than we shouldn't do a binary search in this point (because we can't increase the answer). It can be proved that this solution in avarage case works in $O(logAnswer \cdot nlog^{2}n + n^{2}logn)$ if we shuffle points. It's true because a binary search will be used in avarage only $logn$ times. To prove this fact let's look at probability of binary search to be used in $i$-th step. If all values are different and shuffled it is $\frac{1}{\overline{{s}}}$. It is known that sum of first $n$ elements of this sirie is bounded by $logn$. In this task there are some technical issues you need to know about. For example, we would do a binary search only $O(logn)$ times if we find a stricly incresing subseqence of answers. That's why before using a binary search we should check that we can obtain not current answer but current answer plus some small value. Also we need to understand what "small value" is (it should be something like $eps \cdot curAnswer$, where $eps = 10^{ - 9}$, in another case you will probably have some problems with accuracy).
|
[
"geometry"
] | 3,100
| null |
443
|
A
|
Anton and Letters
|
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
|
In this task you are to count the number of different letters in the set. In my opinion the easiest way to do this looks like this. You just iterate over all small latin letters and check if the string contains it (with built-in functions).
|
[
"constructive algorithms",
"implementation"
] | 800
| null |
443
|
B
|
Kolya and Tandem Repeat
|
Kolya got string $s$ for his birthday, the string consists of small English letters. He immediately added $k$ more characters to the right of the string.
Then Borya came and said that the new string contained a tandem repeat of length $l$ as a substring. How large could $l$ be?
See notes for definition of a tandem repeat.
|
Let's add $k$ question marks to the string. Than we can check all possible starting and ending positions of tandem repeat in a new string. We can check each of them in time $O(n + k)$. We only need to check that some symbols are equal (in our task question mark is equal to every symbol).
|
[
"brute force",
"implementation",
"strings"
] | 1,500
| null |
444
|
A
|
DZY Loves Physics
|
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
\[
\left\{{\frac{v}{e}}{\qquad(e>0)}\right.\qquad(e>0)
\]
where $v$ is the sum of the values of the nodes, $e$ is the sum of the values of the edges.Once DZY got a graph $G$, now he wants to find a connected induced subgraph $G'$ of the graph, such that the density of $G'$ is as large as possible.
An induced subgraph $G'(V', E')$ of a graph $G(V, E)$ is a graph that satisfies:
- $V^{\prime}\subseteq V$;
- edge $(a,b)\in E^{\prime}$ if and only if $a\in V^{\prime}.b\in V^{\prime}$, and edge $(a,b)\in E$;
- the value of an edge in $G'$ is the same as the value of the corresponding edge in $G$, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
|
If there is a connected induced subgraph containing more than $2$ nodes with the maximum density. The density of every connected induced subgraph of it that contains only one edge can be represented as $\frac{\i I+v}{\mathbb{C}}$, where $u, v$ are the values of the two nodes linked by the edge. The density of the bigger connected induced subgraph is at most $\frac{\sum_{u+1}\sum v}{\sum c}$. If $B={\frac{\Sigma_{u+}\Sigma_{v}}{\Sigma c}}$, and for every edge, $\overset{n\neq v}{c}<B$. Then we'll have $u + v < Bc$, and $\textstyle\sum u+\sum v<B\sum c$, and $B>{\frac{\Sigma_{u+1\Sigma v}}{\Sigma c}}$, it leads to contradiction. So just check every single node, and every $2$ nodes linked by an edge. The time complexity is $O(n + m)$.
|
[
"greedy",
"math"
] | 1,600
|
#include <cstdio>
#include <algorithm>
using namespace std;
int n, m, a, b, c, x[1100];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &x[i]);
double ans = 0;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &a, &b, &c);
ans = max(ans, 1.0 * (x[a] + x[b]) / c);
}
printf("%.15lf\n", ans);
}
|
444
|
B
|
DZY Loves FFT
|
DZY loves Fast Fourier Transformation, and he enjoys using it.
Fast Fourier Transformation is an algorithm used to calculate convolution. Specifically, if $a$, $b$ and $c$ are sequences with length $n$, which are indexed from $0$ to $n - 1$, and
\[
c_{i}=\sum_{j=0}^{i}a_{j}b_{i-j}.
\]
We can calculate $c$ fast using Fast Fourier Transformation.
DZY made a little change on this formula. Now
\[
c_{i}=\operatorname*{m}_{j=0}^{i}x_{\lambda}b_{i-j}.
\]
To make things easier, $a$ is a permutation of integers from $1$ to $n$, and $b$ is a sequence only containing $0$ and $1$. Given $a$ and $b$, DZY needs your help to calculate $c$.
Because he is naughty, DZY provides a special way to get $a$ and $b$. What you need is only three integers $n$, $d$, $x$. After getting them, use the code below to generate $a$ and $b$.
\begin{verbatim}
//x is 64-bit variable;
function getNextX() {
x = (x * 37 + 10007) % 1000000007;
return x;
}
function initAB() {
for(i = 0; i < n; i = i + 1){
a[i] = i + 1;
}
for(i = 0; i < n; i = i + 1){
swap(a[i], a[getNextX() % (i + 1)]);
}
for(i = 0; i < n; i = i + 1){
if (i < d)
b[i] = 1;
else
b[i] = 0;
}
for(i = 0; i < n; i = i + 1){
swap(b[i], b[getNextX() % (i + 1)]);
}
}
\end{verbatim}
Operation x % y denotes remainder after division $x$ by $y$. Function swap(x, y) swaps two values $x$ and $y$.
|
Firstly, you should notice that $A$, $B$ are given randomly. Then there're many ways to solve this problem, I just introduce one of them. This algorithm can get $C_{i}$ one by one. Firstly, choose an $s$. Then check if $C_{i}$ equals to $n, n - 1, n - 2... n - s + 1$. If none of is the answer, just calculate $C_{i}$ by brute force. The excepted time complexity to calculate $C_{i - 1}$ is around $s+(1-r)^{s}\,r i$ where $r={\frac{\mathrm{rhe~number~of~in~}}B_{0~}\mathrm{to~}B_{i-1}}$. Just choose an $s$ to make the formula as small as possible. The worst excepted number of operations is around tens of million.
|
[
"probabilities"
] | 2,300
|
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;
int n, d, X, A[110000], B[110000], q[110000], to[110000];
int pu;
int getNextX() {
X = (X * 37LL + 10007) % 1000000007;
return X;
}
int main() {
scanf("%d%d%d", &n, &d, &X);
for (int i = 0; i < n; i = i + 1)
A[i] = i + 1;
for (int i = 0; i < n; i = i + 1)
swap(A[i], A[getNextX() % (i + 1)]);
for (int i = 0; i < n; i = i + 1) {
if (i < d)
B[i] = 1;
else
B[i] = 0;
}
for (int i = 0; i < n; i = i + 1)
swap(B[i], B[getNextX() % (i + 1)]);
for (int i = 0; i < n; i++) if (B[i]) q[++q[0]] = i;
int s = 30;
for (int i = 0; i < n; i++) to[A[i]] = i;
for (int i = 0; i < n; i++) {
int j;
for (j = n; j >= n - s; j--)
if (j > 0 && i >= to[j] && B[i - to[j]]) {
printf("%d\n", j);
break;
}
if (j < n - s) {
int ma = 0;
for (j = 1; j <= q[0] && q[j] <= i; j++)
ma = max(ma, A[i - q[j]]);
printf("%d\n", ma);
}
}
}
|
444
|
C
|
DZY Loves Colors
|
DZY loves colors, and he enjoys painting.
On a colorful day, DZY gets a colorful ribbon, which consists of $n$ units (they are numbered from $1$ to $n$ from left to right). The color of the $i$-th unit of the ribbon is $i$ at first. It is colorful enough, but we still consider that the colorfulness of each unit is $0$ at first.
DZY loves painting, we know. He takes up a paintbrush with color $x$ and uses it to draw a line on the ribbon. In such a case some contiguous units are painted. Imagine that the color of unit $i$ currently is $y$. When it is painted by this paintbrush, the color of the unit becomes $x$, and the colorfulness of the unit increases by $|x - y|$.
DZY wants to perform $m$ operations, each operation can be one of the following:
- Paint all the units with numbers between $l$ and $r$ (both inclusive) with color $x$.
- Ask the sum of colorfulness of the units between $l$ and $r$ (both inclusive).
Can you help DZY?
|
The only thing you need to notice is that if there are many continuous units with the same uppermost color, just merge them in one big unit. Every time painting continuous units, such big units will only increase by at most $3$. Then you can use STL set to solve it. But anyway, a segment tree is useful enough, check the C++ solution here. The time complexity is $O(n\log n)$.
|
[
"data structures"
] | 2,400
|
#include <cstdio>
#include <algorithm>
using namespace std;
int n, m, t, l, r, x, mark[410000];
long long delta[410000], sum[410000];
void read(int &x) {
char k;
for (k = getchar(); k <= 32; k = getchar());
for (x = 0; '0' <= k; k = getchar()) x = x * 10 + k - '0';
}
void mkt(int k, int q, int h) {
if (q < h) {
mkt(k * 2, q, (q + h) / 2);
mkt(k * 2 + 1, (q + h) / 2 + 1, h);
mark[k] = 0;
}else mark[k] = q;
}
long long query(int k, int q, int h, int l, int r) {
if (l <= q && h <= r) return sum[k];
if (r <= (q + h) / 2) return query(k * 2, q, (q + h) / 2, l, r) + 1LL * delta[k] * (r - l + 1);
if ((q + h) / 2 < l) return query(k * 2 + 1, (q + h) / 2 + 1, h, l, r) + 1LL * delta[k] * (r - l + 1);
return query(k * 2, q, (q + h) / 2, l, (q + h) / 2) + query(k * 2 + 1, (q + h) / 2 + 1, h, (q + h) / 2 + 1, r) + 1LL * delta[k] * (r - l + 1);
}
void Clear(int k, int q, int h) {
if (mark[k] > 0) {
delta[k] += abs(mark[k] - x);
sum[k] += 1LL * abs(mark[k] - x) * (h - q + 1);
}else {
Clear(k * 2, q, (q + h) / 2);
Clear(k * 2 + 1, (q + h) / 2 + 1, h);
sum[k] = sum[k * 2] + sum[k * 2 + 1] + 1LL * delta[k] * (h - q + 1);
}
mark[k] = -1;
}
void modify(int k, int q, int h) {
if (l <= q && h <= r) Clear(k, q, h), mark[k] = x;
else {
if (mark[k] > 0) mark[k * 2] = mark[k * 2 + 1] = mark[k], mark[k] = 0;
if (r <= (q + h) / 2) modify(k * 2, q, (q + h) / 2);
else if ((q + h) / 2 < l) modify(k * 2 + 1, (q + h) / 2 + 1, h);
else modify(k * 2, q, (q + h) / 2), modify(k * 2 + 1, (q + h) / 2 + 1, h);
mark[k] = 0;
sum[k] = sum[k * 2] + sum[k * 2 + 1] + 1LL * delta[k] * (h - q + 1);
}
}
int main() {
read(n); read(m);
mkt(1, 1, n);
while (m--) {
read(t); read(l); read(r);
if (t == 1) {
read(x);
modify(1, 1, n);
}else {
printf("%I64d\n", query(1, 1, n, l, r));
}
}
}
|
444
|
D
|
DZY Loves Strings
|
DZY loves strings, and he enjoys collecting them.
In China, many people like to use strings containing their names' initials, for example: xyz, jcvb, dzy, dyh.
Once DZY found a lucky string $s$. A lot of pairs of good friends came to DZY when they heard about the news. The first member of the $i$-th pair has name $a_{i}$, the second one has name $b_{i}$. Each pair wondered if there is a substring of the lucky string containing both of their names. If so, they want to find the one with minimum length, which can give them good luck and make their friendship last forever.
Please help DZY for each pair find the minimum length of the substring of $s$ that contains both $a_{i}$ and $b_{i}$, or point out that such substring doesn't exist.
A substring of $s$ is a string $s_{l}s_{l + 1}... s_{r}$ for some integers $l, r$ $(1 ≤ l ≤ r ≤ |s|)$. The length of such the substring is $(r - l + 1)$.
A string $p$ contains some another string $q$ if there is a substring of $p$ equal to $q$.
|
We can solve a subproblem in which all the query strings are characters only first. The problem becomes calculating the shortest substring containing two given characters. If character $ch$ appears more than $T$ times in $S$, use brute force with time complexity $O(|S|)$ to calculate all the queries containing $ch$. Obviously, there are at most $O(|S| / T)$ such $ch$ in $S$. Otherwise, we consider two sorted sequences, just merge them with time complexity $O(T)$(Both of the two characters appear at most $T$ times). Being merging, you can get the answer. So the complexity is $O(TQ + |S|^{2} / T)$. We can choose $T=|S|/{\sqrt{Q}}$, then the complexity is $O(|S|{\sqrt{Q}})$. And short substring is almost the same with characters.
|
[
"binary search",
"hashing",
"strings",
"two pointers"
] | 2,500
|
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define rep(i,x,y) for(i=x;i<=y;i++)
#define pb push_back
#define mp make_pair
#define upmin(x,y) x=min(x,y)
const int L=50010,R=4,N=L*R,Q=100010,inf=int(1e9);
int l,q,g,all,i,j,k,p,x,y,p1,p2,res,tot;char s[L],s0[11];
int h[600000],ans[Q],d[R+1][L],tmp[N],li[N],l2[N],pos[N],num[N],vg[N],la[L],ne[L];vector<int> v[N];
struct ask{int x,y,lx,ly,nn;}c[Q];
bool cmp(ask a,ask b){return mp(a.x,a.y)<mp(b.x,b.y);}
int ins(int x){if(h[x])return h[x];num[++tot]=x;return h[x]=tot;}
int getstr(int&l0){
scanf("%s",s0+1);int i,res;l0=strlen(s0+1);
for(res=0,i=1;i<=l0;i++)res=res*27+(s0[i]-'a'+1);return res;
}
void calcd(int id,int l0){
int i,j,k,la0,ne0,now;
rep(j,1,R){
for(int k=0;k<=l;k++)la[k]=-inf,ne[k]=inf;
for(int k=0;k<vg[id];k++){
now=v[id][k];
la0=(k==0)?1:v[id][k-1]+1;
ne0=(k==vg[id]-1)?l:v[id][k+1]-1;
rep(i,now,ne0)la[i]=now;
rep(i,la0,now)ne[i]=now;
}
rep(i,1,l)d[j][i]=min(max(i+j,ne[i]+l0)-i,max(i+j,la[i]+l0)-la[i]);
}
}
int main(){
scanf("%s%d",s+1,&q);l=strlen(s+1);
rep(i,1,l)for(res=0,j=1;j<=R&&i+j-1<=l;j++)
l2[++all]=j,v[pos[all]=ins(res=res*27+(s[i+j-1]-'a'+1))].pb(li[all]=i);
rep(i,1,tot)vg[i]=v[i].size();
rep(i,1,q){
int ida=h[getstr(p1)],idb=h[getstr(p2)];
if(ida==0||idb==0)ans[i]=-1;
else{ans[i]=inf;if(vg[ida]<vg[idb])swap(ida,ida);c[++g]=(ask){ida,idb,p1,p2,i};}
}
sort(c+1,c+1+g,cmp);
for(i=1;i<=g;i=j+1){
long long totcnt=0;
for(j=i;j<=g&&c[j].x==c[i].x;j++)totcnt+=vg[c[j].y]+vg[c[i].x];j--;
if(totcnt>all){
calcd(c[i].x,c[i].lx);
rep(k,1,tot)tmp[k]=inf;
rep(k,1,all)upmin(tmp[pos[k]],d[l2[k]][li[k]]);
rep(k,i,j)upmin(ans[c[k].nn],tmp[c[k].y]);
}
else
rep(k,i,j)
for(p1=p2=0,x=c[k].x,y=c[k].y;p1<vg[x]&&p2<vg[y];v[x][p1]<=v[y][p2]?p1++:p2++)
upmin(ans[c[k].nn],max(v[x][p1]+c[k].lx,v[y][p2]+c[k].ly)-min(v[x][p1],v[y][p2]));
}
rep(i,1,q)printf("%d\n",ans[i]);
return 0;
}
|
444
|
E
|
DZY Loves Planting
|
DZY loves planting, and he enjoys solving tree problems.
DZY has a weighted tree (connected undirected graph without cycles) containing $n$ nodes (they are numbered from $1$ to $n$). He defines the function $g(x, y)$ $(1 ≤ x, y ≤ n)$ as the longest edge in the shortest path between nodes $x$ and $y$. Specially $g(z, z) = 0$ for every $z$.
For every integer sequence $p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$, DZY defines $f(p)$ as $\operatorname*{min}_{i=1}g(i,p_{i})$.
DZY wants to find such a sequence $p$ that $f(p)$ has maximum possible value. But there is one more restriction: the element $j$ can appear in $p$ at most $x_{j}$ times.
Please, find the maximum possible $f(p)$ under the described restrictions.
|
Firstly, use binary search. We need to determine whether the answer can be bigger than $L$. Then, every pair $(i, P_{i})$ must contain at least one edge which length is bigger than $L$. It's a problem like bipartite graph matching, and we can use maxflow algorithm to solve it. We create $2$ nodes for every node $i$ of the original tree. We call one of the nodes $L_{i}$, and the other $R_{i}$. And we need a source $s$ and a terminal $t$. Link $s$ to every $L_{i}$ with upper bound $1$, and link $R_{i}$ to $t$ with upper bound $x_{i}$. Then if the path between node $a$ and node $b$ contains an edge with value larger than $L$, link $L_{a}$ and $R_{b}$ with upper bound $1$. This means they can match. Every time we build such graph, we must check $O(N^{2})$ pairs of nodes, so number of edges of the network is $O(N^{2})$. We can make it better. Consider the process of \texttt{Divide and Conquer} of a tree, This algorithm can either based on node or edge. And The one based on edge is simpler in this problem. Now, there are two subtrees $T_{x}$, $T_{y}$ on two sides, we record the maximum edge from every node $i$ to the current edge we split, we call it $MAXL_{i}$. Suppose $L_{x}$ is in $T_{x}$ and $R_{y}$ is in $T_{y}$ (it is almost the same in contrast). We create two new nodes $G_{x}$, $G_{y}$ in the network to represent the two subtrees. Add edges $(L_{i}, G_{x}, \infty )$ ($i$ is in $T_{x}$) and edges $(G_{y}, R_{i}, \infty )$ ($i$ is in $T_{y}$). If $i$ is in $T_{x}$ and $MAXL_{i} > L$, we add an edge $(L_{i}, G_{y}, \infty )$. If $j$ is in $T_{y}$ and $MAXL_{j} > L$, we add an edge $(G_{x}, R_{j}, \infty )$. Then use maxflow algorithm. The number of nodes in the network is $O(N)$ and the number of edges in the network is $O(N\log N)$. So the total complexity is $O(N^{2}\log^{2}N)$ with really small constant.
|
[
"binary search",
"dsu",
"trees"
] | 2,700
|
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define rep(i,x,y) for(i=x;i<=y;i++)
#define REP(i,x,y) for(int i=(x);i<=(y);i++)
#define CL(S,x) memset(S,x,sizeof(S))
#define CP(S1,S2) memcpy(S1,S2,sizeof(S2))
#define pb push_back
const int N=12010,inf=int(1e9),V=100010,E=500010;
int n,n0,i,j,k,l,r,p,x,y,z,L,X[N],o[N];
struct FlowG{
int S,T,N,edge,e[E],b[E],c[E],fir[V],last[V],vh[V],h[V],cur[V],pre[V];
void clear(){edge=1;CL(fir,0);}
void add2(int x,int y,int z){e[++edge]=y;c[edge]=z;b[edge]=fir[x];fir[x]=edge;}
void add(int x,int y,int z){add2(x,y,z);add2(y,x,0);}
int sap(){
int i,k,p,flow,minh,ans=0;CL(h,0);CL(vh,0);vh[0]=N;CP(cur,fir);CL(pre,0);pre[S]=S;
for(i=S;h[S]<N;){
if(i==T){
flow=inf;for(p=S;p!=T;p=e[cur[p]])flow=min(flow,c[cur[p]]);
ans+=flow;for(p=S;p!=T;p=e[cur[p]])c[cur[p]]-=flow,c[cur[p]^1]+=flow;i=S;
}
for(k=cur[i];k;k=b[k])
if(c[k]&&h[e[k]]+1==h[i]){cur[i]=k;pre[e[k]]=i;i=e[k];break;}
if(!k){
if(--vh[h[i]]==0)break;
cur[i]=fir[i];minh=N;for(k=cur[i];k;k=b[k])if(c[k])minh=min(minh,h[e[k]]+1);
++vh[h[i]=minh];i=pre[i];
}
}
return ans;
}
}F;
struct graph{
int edge,fir[N],e[N],b[N],w[N];bool done[N];
int fa[N],fae[N],sz[N],ms[N],st[N],st1[N],st2[N];
void clear(){edge=1;CL(fir,0);}void add2(int x,int y,int z){e[++edge]=y;w[edge]=z;b[edge]=fir[x];fir[x]=edge;}
void add(int x,int y,int z){add2(x,y,z);add2(y,x,z);}
int dfs(int i,int f,int ma){st[++st[0]]=i;fa[i]=f;sz[i]=1;ms[i]=ma;for(int k=fir[i];k;k=b[k])if(!done[k]&&e[k]!=f)fae[e[k]]=k,sz[i]+=dfs(e[k],i,max(ma,w[k]));return sz[i];}
void fadd(){
int t1=++F.N;REP(p,1,st1[0])F.add(st1[p],t1,inf); REP(p,1,st2[0])if(ms[st2[p]]>=L)F.add(t1,n+st2[p],inf);
int t2=++F.N;REP(p,1,st1[0])if(ms[st1[p]]>=L)F.add(st1[p],t2,inf); REP(p,1,st2[0])F.add(t2,n+st2[p],inf);
}
void fun(int r){
st[0]=0;int sz0=dfs(r,0,0),best=N,A,B,O,p;if(sz0<=1)return;
rep(p,2,st[0]){int i=st[p],tt;if((tt=max(sz0-sz[i],sz[i]))<best)best=tt,A=i,B=fa[i],O=fae[i];}
done[O]=done[O^1]=1;
st[0]=0;dfs(A,0,w[O]);rep(i,0,st[0])st1[i]=st[i];
st[0]=0;dfs(B,0,w[O]);rep(i,0,st[0])st2[i]=st[i];
fadd();rep(i,0,sz0)swap(st1[i],st2[i]);fadd();
fun(A);fun(B);
}
bool ok(){
F.clear();F.S=2*n+1;F.N=F.T=2*n+2;REP(i,1,n0)F.add(F.S,i,1);REP(i,1,n0)F.add(n+i,F.T,X[i]);
CL(done,0);fun(1);return F.sap()==n0;
}
}H;
struct ori{
vector<int> e[N],ew[N];int li[N],lw[N];
void adde(int x,int y,int z){e[x].pb(y);ew[x].pb(z);}
void work(int x,int y,int f){
if(x==y){H.add(f,li[x],lw[x]);return;}
int nod=++n;H.add(f,nod,0);work(x,(x+y)/2,nod);work((x+y)/2+1,y,nod);
}
void bui(int i,int f){
li[0]=0;for(int k=0;k<e[i].size();k++)if(e[i][k]!=f)li[++li[0]]=e[i][k],lw[li[0]]=ew[i][k];
if(li[0])work(1,li[0],i);for(int k=0;k<e[i].size();k++)if(e[i][k]!=f)bui(e[i][k],i);
}
}G;
int main(){
scanf("%d",&n);n0=n;
rep(i,1,n-1)scanf("%d%d%d",&x,&y,&z),G.adde(x,y,z),G.adde(y,x,z),o[i]=z;rep(i,1,n)scanf("%d",&X[i]);
sort(o+1,o+1+(n-1));o[0]=1;rep(i,2,n-1)if(o[i]!=o[i-1])o[++o[0]]=o[i];
H.clear();G.bui(1,0);
for(l=1,r=o[0];l<r;){int mid=(l+r+1)/2;L=o[mid];if(H.ok())l=mid;else r=mid-1;}printf("%d\n",o[l]);
return 0;
}
|
445
|
A
|
DZY Loves Chessboard
|
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of $n$ rows and $m$ columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
|
Just output the chessboard like this: WBWBWBWB... BWBWBWBW... WBWBWBWB... ... Don't forget to left '-' as it is. The time complexity is $O(nm)$.
|
[
"dfs and similar",
"implementation"
] | 1,200
|
#include <cstdio>
using namespace std;
int n, m;
char S[1100];
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%s", S);
for (int j = 0; j < m; j++)
if (S[j] == '.') {
if ((i + j) & 1) S[j] = 'W';
else S[j] = 'B';
}
printf("%s\n", S);
}
}
|
445
|
B
|
DZY Loves Chemistry
|
DZY loves chemistry, and he enjoys mixing chemicals.
DZY has $n$ chemicals, and $m$ pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is $1$. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by $2$. Otherwise the danger remains as it is.
Find the maximum possible danger after pouring all the chemicals one by one in optimal order.
|
It's easy to find that answer is equal to $2^{n - v}$, where $v$ is the number of connected components.
|
[
"dfs and similar",
"dsu",
"greedy"
] | 1,400
|
#include <cstdio>
using namespace std;
int n, m, fa[100], x, y;
int gf(int x) {
if (fa[x] != x) fa[x] = gf(fa[x]);
return fa[x];
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i;
while (m--) {
scanf("%d%d", &x, &y);
fa[gf(x)] = gf(y);
}
long long ans = (1LL << n);
for (int i = 1; i <= n; i++)
if (gf(i) == i) ans /= 2;
printf("%I64d\n", ans);
}
|
446
|
A
|
DZY Loves Sequences
|
DZY has a sequence $a$, consisting of $n$ integers.
We'll call a sequence $a_{i}, a_{i + 1}, ..., a_{j}$ $(1 ≤ i ≤ j ≤ n)$ a subsegment of the sequence $a$. The value $(j - i + 1)$ denotes the length of the subsegment.
Your task is to find the longest subsegment of $a$, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.
You only need to output the length of the subsegment you find.
|
We can first calculate $l_{i}$ for each $1 \le i \le n$, satisfying $a_{i - li + 1} < a_{i - li + 2} < ... < a_{i}$, which $l_{i}$ is maximal. Then calculate $r_{i}$, satisfying $a_{i} < a_{i + 1} < ... < a_{i + ri - 1}$, which $r_{i}$ is also maximal. Update the answer $a n s=\operatorname*{max}(a n s,l_{i-1}+1+r_{i+1})$, when $a_{i - 1} + 1 < a_{i + 1}$. It's easy to solve this problem in $O(n)$.
|
[
"dp",
"implementation",
"two pointers"
] | 1,600
| null |
446
|
B
|
DZY Loves Modification
|
As we know, DZY loves playing games. One day DZY decided to play with a $n × m$ matrix. To be more precise, he decided to modify the matrix with exactly $k$ operations.
Each modification is one of the following:
- Pick some row of the matrix and decrease each element of the row by $p$. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing.
- Pick some column of the matrix and decrease each element of the column by $p$. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing.
DZY wants to know: what is the largest total value of pleasure he could get after performing exactly $k$ modifications? Please, help him to calculate this value.
|
If $p = 0$, apperently the best choice is choosing the row or column which can give greatest pleasure value each time. Ignore $p$ first,then we can get a greatest number $ans$. Then if we choose rows for $i$ times, choose columns for $k - i$ times, $ans$ should subtract $(k - i) \times i \times p$. So we could enumerate i form 0 to k and calculate $ans_{i} - (k - i) * i * p$ each time, max ${ans_{i} - (k - i) * i * p}$ is the maximum possible pleasure value DZY could get. Let $a_{i}$ be the maximum pleasure value we can get after choosing $i$ rows and $b_{i}$ be the maximum pleasure value we can get after choosing $i$ columns. Then $ans_{i} = a_{i} + b_{k - i}$. We can use two priority queues to calculate $a_{i}$ and $b_{i}$ quickly.
|
[
"brute force",
"data structures",
"greedy"
] | 2,000
| null |
446
|
C
|
DZY Loves Fibonacci Numbers
|
In mathematical terms, the sequence $F_{n}$ of Fibonacci numbers is defined by the recurrence relation
\[
F_{1} = 1; F_{2} = 1; F_{n} = F_{n - 1} + F_{n - 2} (n > 2).
\]
DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Moreover, there are $m$ queries, each query has one of the two types:
- Format of the query "$1 l r$". In reply to the query, you need to add $F_{i - l + 1}$ to each element $a_{i}$, where $l ≤ i ≤ r$.
- Format of the query "$2 l r$". In reply to the query you should output the value of $\textstyle\sum_{i=1}^{r}a_{i}$ modulo $1000000009 (10^{9} + 9)$.
Help DZY reply to all the queries.
|
As we know, $F_{n}=\stackrel{\sqrt{5}}{5}\left[\left(\frac{1\!+\!\sqrt{5}}{2}\right)^{n}-\left(\frac{1\!-\!\sqrt{5}}{2}\right)^{n}\right]$ Fortunately, we find that $383008016^{2}\equiv5({\mathrm{mod}}\;10^{9}+9)$ So, $383008016\equiv{\sqrt{5}}({\mathrm{mod~}}10^{9}+9)$ With multiplicative inverse, we find, $\textstyle{\frac{\sqrt{5}}{5}}\equiv276601605(\mathrm{mod}\ 10^{9}+9)$ $\frac{1+\sqrt{5}}{2}\equiv691504013(\mathrm{mod}\ 10^{9}+9)$ ${\frac{1-{\sqrt{5}}}{2}}\equiv308495997({\mathrm{mod~}}10^{9}+9)$ Now, $F_{n}\equiv27601605(691504013^{n}-308495997^{n})(\mathrm{mod}\ 10^{9}+9)$ As you see, we can just maintain the sum of a Geometric progression $\{a_{n}\}=R^{n}$ This is a simple problem which can be solved with segment tree in $O(q\log n)$.
|
[
"data structures",
"math",
"number theory"
] | 2,400
| null |
446
|
D
|
DZY Loves Games
|
Today DZY begins to play an old game. In this game, he is in a big maze with $n$ rooms connected by $m$ corridors (each corridor allows to move in both directions). You can assume that all the rooms are connected with corridors directly or indirectly.
DZY has got lost in the maze. Currently he is in the first room and has $k$ lives. He will act like the follows:
- Firstly he will randomly pick one of the corridors going from his current room. Each outgoing corridor has the same probability to be picked.
- Then he will go through the corridor and then the process repeats.
There are some rooms which have traps in them. The first room definitely has no trap, the $n$-th room definitely has a trap. Each time DZY enters one of these rooms, he will lost one life. Now, DZY knows that if he enters the $n$-th room with exactly 2 lives, firstly he will lost one live, but then he will open a bonus round. He wants to know the probability for him to open the bonus round. Please, help him.
|
Define important room as the trap room. Let $w(u, v)$ be equal to the probability that DZY starts at $u$ ($u$ is a important room or $u$=1) and $v$ is the next important room DZY arrived. For each $u$, we can calculate $w(u, v)$ in $O(n^{3})$ by gauss elimination. Let $A_{i}$ be equal to the $i$'th important room DZY arrived. So $A_{k - 1} = n$, specially $A_{0} = 1$. Let $ans$ be the probability for DZY to open the bonus round. Easily we can know $a n s=\prod_{0<i<k-2}w(A_{i},A_{i+1})$. So we can calculate ans in $O(a^{3}\log k)$($a$ is equal to the number of important rooms) by matrix multiplication. So we can solve the problem in $O(n^{4}+a^{3}\mathrm{log}k)$. we should optimize this algorithm. We can find that each time we do gauss elimination, the variable matrix is unchanged. So we can do gauss elimination once to do preprocessing in $O(n^{3})$. Then for each time calculating $w(u, v)$, the only thing to do is substitute the constants. In this way we can calculate $w(u, v)$ in $O(n^{3})$. In this way, we can solve this problem in $O(n^{3}+a^{3}\mathrm{log}k)$
|
[
"math",
"matrices",
"probabilities"
] | 2,800
| null |
446
|
E
|
DZY Loves Bridges
|
DZY owns $2^{m}$ islands near his home, numbered from $1$ to $2^{m}$. He loves building bridges to connect the islands. Every bridge he builds takes one day's time to walk across.
DZY has a strange rule of building the bridges. For every pair of islands $u, v (u ≠ v)$, he has built $2^{k}$ different bridges connecting them, where $k=\operatorname*{max}\left\{k:2^{k}|a b s(u-v)\right\}$ ($a|b$ means $b$ is divisible by $a$). These bridges are bidirectional.
Also, DZY has built some bridges connecting his home with the islands. Specifically, there are $a_{i}$ different bridges from his home to the $i$-th island. These are one-way bridges, so after he leaves his home he will never come back.
DZY decides to go to the islands for sightseeing. At first he is at home. He chooses and walks across one of the bridges connecting with his home, and arrives at some island. After that, he will spend $t$ day(s) on the islands. Each day, he can choose to stay and rest, or to walk to another island across the bridge. It is allowed to stay at an island for more than one day. It's also allowed to cross one bridge more than once.
Suppose that right after the $t$-th day DZY stands at the $i$-th island. Let $ans[i]$ be the number of ways for DZY to reach the $i$-th island after $t$-th day. Your task is to calculate $ans[i]$ for each $i$ modulo $1051131$.
|
Let $n = 2^{m}$. For convenience, we use indices $0, 1, ..., n - 1$ here instead of $1, 2, ..., n$, so we define $a_{0} = a_{n}$. Obviously this problem requires matrix multiplication. We define row vector $A=(a_{0},a_{1},\cdot\cdot\cdot,a_{n-1})$, and matrix $B=(b_{i j})$, where $b_{ii} = 1$, $b_{i j}=\operatorname*{max}\left\{2^{k}:2^{k}|i-j\right\}(i\not=j)$. The answer is row vector $C=A B^{i}$. Since $n$ can be up to $3 \times 10^{7}$, we need a more efficient way to calculate. Let $B_{k}$ denote the matrix $\boldsymbol{B}$ when $m = k$. For example, $B_{3}=\left({\begin{array}{c c c c c c c c c}{{1}}&{{1}}&{{2}}&{{1}}&{{4}}&{{1}}&{{2}}&{{1}}\\ {{1}}&{{1}}&{{2}}&{{1}}&{{4}}&{{1}}&{{2}}&{{2}}\\ {{2}}&{{1}}&{{1}}&{{2}}&{{1}}&{{1}}&{{1}}&{{1}}\\ {{1}}&{{1}}&{{1}}&{{1}}&{{2}}&{{1}}&{{1}}&{{1}}\\ {{1}}&{{1}}&{{1}}&{{2}}&{{1}}&{{1}}&{{1}}\\ {{2}}&{{1}}&{{4}}&{{1}}&{{2}}&{{1}}&{{1}}\\ {{2}}&{{1}}&{{4}}&{{1}}&{{2}}&{{1}}&{{1}}\end{array}}\right)$ Define $B_{n}=(1)$, then we can easily find that $B_{k+1}=\left(_{B_{k}+(2^{k}-1)I}\begin{array}{c}{{B_{k}+(2^{k}-1)I}}\\ {{B_{k}}}\end{array}\right)$ where ${\mathbf I}$ denotes the identity matrix. For an $n \times n$ matrix $X$ and a constant $r$, we can prove by induction that $\left({\begin{array}{l l}{X}&{X+r I}\\ {X+r I}&{X}\end{array}}\right)^{t}={\frac{1}{2}}\left((2X+r I)^{t}+(-r)^{t}I}&{(2X+r I)^{t}-(-r)^{t}I\right)$ Let $ \alpha _{1}, \alpha _{2}$ be two $1 \times n$ vectors, then we have $\begin{array}{c}{{\left(\alpha_{1}\,\,\,\,\alpha_{2}\right)\left({_X+r I\,\,X}_{1}^{\phantom{\dagger}X+r I}\right)^{t}}}\\ {{\frac{\left(\alpha_{1}+\alpha_{2}\right)\left({2X+r I+r I}\right)^{t}-\alpha_{2}\right)\left(-r\right)^{t}}{\left(\alpha_{1}+\alpha_{2}\right)\left({2X+r I\right)^{t}-\left(\alpha_{1}-\alpha_{2}\right)\left(-r\right)^{t}}I\right)}}\end{array}$ This result seems useful. Suppose we want to find $A(p B_{k+1}+q I)^{t}$, where $A=\left(\alpha_{1}\ \ \alpha_{2}\right)$, we have $\begin{array}{l l}{{}}&{{A/B_{k+1}+q I^{\prime}}}\\ {{(\alpha_{1}+\alpha_{2})\left({}_{p}B_{k}+\alpha I+\nu(z^{\prime}p-\nu-q)I^{\prime}\right)^{\prime}}}&{{\nu B_{k}+q I^{\prime}\left(2^{a}p-p-q I\right)^{\prime}}}\\ {{}}&{{\left[(\alpha_{1}+\alpha_{2})(2p-\nu-\nu-q I^{\prime}+\nu+q I^{\prime})^{\prime}+(\alpha_{1}-\alpha_{2})(2p+(z^{a}p+\nu+\nu+q I^{\prime})^{\prime}-(\alpha_{1}-\alpha_{2})(2\nu-\nu-\nu+q I^{\prime})^{\prime}-(\alpha_{1}-\alpha_{2})(-2^{a}p+\nu+\bar{\nu})^{\prime}+\bar{\nu}})^{\prime}}\end{array}$ so we just need to find $(\alpha_{1}+\alpha_{2})(2p B_{k}+(2^{k}p-p+q)I)^{t}$, which is a self-similar problem. By recursion, it can be solved in time $T(n) = T(n / 2) + O(n) = O(n)$.
|
[
"math",
"matrices"
] | 3,100
| null |
447
|
A
|
DZY Loves Hash
|
DZY has a hash table with $p$ buckets, numbered from $0$ to $p - 1$. He wants to insert $n$ numbers, in the order they are given, into the hash table. For the $i$-th number $x_{i}$, DZY will put it into the bucket numbered $h(x_{i})$, where $h(x)$ is the hash function. In this problem we will assume, that $h(x) = x mod p$. Operation $a mod b$ denotes taking a remainder after division $a$ by $b$.
However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the $i$-th insertion, you should output $i$. If no conflict happens, just output -1.
|
We just need an array to store the numbers inserted and check whether a conflict happens. It's easy.
|
[
"implementation"
] | 800
| null |
447
|
B
|
DZY Loves Strings
|
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter $c$ DZY knows its value $w_{c}$. For each special string $s = s_{1}s_{2}... s_{|s|}$ ($|s|$ is the length of the string) he represents its value with a function $f(s)$, where
\[
f(s)=\sum_{i=1}^{\mathbb{N}_{1}}(w_{s_{i}}\cdot i).
\]
Now DZY has a string $s$. He wants to insert $k$ lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
|
Firstly the optimal way is to insert letter with maximal $w_{i}$. Let $n u m=\mathbf{max}${$w_{i}$}. If we insert this character into the $k$'th position, the extra value we could get is equal to $\begin{array}{l}{{\sum_{i=k}^{n}w_{s_{i}}+n u m\star k=\sum_{i=1}^{k}n u m+\sum_{i=k}^{n}w_{s_{i}}}}\end{array}$. Because of $w_{si} \le num$, when $k = n + 1$, we can get the largest extra value. So if we insert the k letters at the end of $S$, we will get the largest possible value.
|
[
"greedy",
"implementation"
] | 1,000
| null |
448
|
A
|
Rewards
|
Bizon the Champion is called the Champion for a reason.
Bizon the Champion has recently got a present — a new glass cupboard with $n$ shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has $a_{1}$ first prize cups, $a_{2}$ second prize cups and $a_{3}$ third prize cups. Besides, he has $b_{1}$ first prize medals, $b_{2}$ second prize medals and $b_{3}$ third prize medals.
Naturally, the rewards in the cupboard must look good, that's why Bizon the Champion decided to follow the rules:
- any shelf cannot contain both cups and medals at the same time;
- no shelf can contain more than five cups;
- no shelf can have more than ten medals.
Help Bizon the Champion find out if we can put all the rewards so that all the conditions are fulfilled.
|
Because rewards of one type can be on one shelf, lets calculate number of cups - $a$ and number of medals - $b$. Minimum number of shelves that will be required for all cups can be found by formula $(a + 5 - 1) / 5$. The same with shelves with medals: $(b + 10 - 1) / 10$. If sum of this two values more than $n$ then answer is "NO" and "YES" otherwise.
|
[
"implementation"
] | 800
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e6+6;
int main(){
//freopen("input.txt","r",stdin);// freopen("output.txt","w",stdout);
int a1,a2,a3,b1,b2,b3,K;
cin>>a1>>a2>>a3>>b1>>b2>>b3>>K;
int a = (a1+a2+a3 + 4) / 5;
int b = (b1+b2+b3 + 9) / 10;
cout<<(a+b<=K ? "YES" : "NO")<<endl;
return 0;
}
|
448
|
B
|
Suffix Structures
|
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team.
At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), $s$ and $t$. You need to transform word $s$ into word $t$". The task looked simple to the guys because they know the suffix data structures well. Bizon Senior loves suffix automaton. By applying it once to a string, he can remove from this string any single character. Bizon Middle knows suffix array well. By applying it once to a string, he can swap any two characters of this string. The guys do not know anything about the suffix tree, but it can help them do much more.
Bizon the Champion wonders whether the "Bizons" can solve the problem. Perhaps, the solution do not require both data structures. Find out whether the guys can solve the problem and if they can, how do they do it? Can they solve it either only with use of suffix automaton or only with use of suffix array or they need both structures? Note that any structure may be used an unlimited number of times, the structures may be used in any order.
|
Consider each case separately. If we use only suffix automaton then $s$ transform to some of its subsequence. Checking that $t$ is a subsequence of $s$ can be performed in different ways. Easiest and fastest - well-known two pointers method. In case of using suffix array we can get every permutation of $s$. If it is not obvious for you, try to think. Thus, $s$ and $t$ must be anagrams. If we count number of each letter in each string, we can check this. If every letter appears in $s$ the same times as in $t$ then words are anagrams. In case of using both structures strategy is: remove some letters and shuffle the rest. It is possible if every letter appears in $s$ not less times than in $t$. Otherwise it is impossible to make $t$ from $s$. Total complexity $O(|s| + |t| + 26)$.
|
[
"implementation",
"strings"
] | 1,400
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e5+5;
int cnt[30];
char s[N], t[N];
void solve(){
scanf("%s%s",&s,&t);
int n = strlen(s);
int m = strlen(t);
memset(cnt, 0, sizeof cnt);
bool sau = false;
for(int i=0,j=0; i<n; ++i){
if(j<m && s[i]==t[j]) ++j;
if(j==m) sau = true;
}
for(int i=0;i<n;++i) cnt[s[i]-'a']++;
for(int i=0;i<m;++i) cnt[t[i]-'a']--;
bool sar = true;
bool all = true;
for(int i=0;i<26;++i){
sar&=cnt[i]==0;
all&=cnt[i]>=0;
}
if(sau) cout<<"automaton"<<endl; else
if(sar) cout<<"array"<<endl; else
if(all) cout<<"both"<<endl; else
cout<<"need tree"<<endl;
}
int main(){
//freopen("input.txt","r",stdin);// freopen("output.txt","w",stdout);
solve();
return 0;
}
|
448
|
C
|
Painting Fence
|
Bizon the Champion isn't just attentive, he also is very hardworking.
Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as $n$ vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the $i$-th plank has the width of $1$ meter and the height of $a_{i}$ meters.
Bizon the Champion bought a brush in the shop, the brush's width is $1$ meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.
|
To solve this problem we need to understand some little things. First, every horizontally stroke must be as widely as possible. Second, under every horizontally stroke should be only horizontally strokes. So, if bottom of fence painted by horizontally stroke then number of this strokes must at least $min(a_{1}, a_{2}, ..., a_{n})$. These strokes maybe divides fence into some unpainted disconnected parts. For all of these parts we need to sum they answers. Now its clearly that solution is recursive. It takes segment $[l, r]$ and height of painted bottom $h$. But we must not forget about situation when all planks painted with vertically strokes. In this case answer must be limited by $r - l + 1$ (length of segment). With given constrains of $n$ we can find minimum on segment by looking all the elements from segment. Complexity in this case will be $O(n^{2})$. But if we use for example segment tree, we can achieve $O(nlogn)$ complexity.
|
[
"divide and conquer",
"dp",
"greedy"
] | 1,900
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e6+6;
const int T = 1e6+6;
int a[N];
int t[T], d;
int rmq(int i, int j){
int r = i;
for(i+=d,j+=d; i<=j; ++i>>=1,--j>>=1){
if(i&1) r=a[r]>a[t[i]]?t[i]:r;
if(~j&1) r=a[r]>a[t[j]]?t[j]:r;
}
return r;
}
int calc(int l, int r, int h){
if(l>r) return 0;
int m = rmq(l,r);
int mn = a[m];
int res = min(r-l+1, calc(l,m-1,mn)+calc(m+1,r,mn)+mn-h);
return res;
}
int main(){
//freopen("input.txt","r",stdin);// freopen("output.txt","w",stdout);
int n, m;
scanf("%d",&n);
for(int i=0;i<n;++i) scanf("%d",&a[i]);
a[n] = 2e9;
for(d=1;d<n;d<<=1);
for(int i=0;i<n;++i) t[i+d]=i;
for(int i=n+d;i<d+d;++i) t[i]=n;
for(int i=d-1;i;--i) t[i]=a[t[i*2]]<a[t[i*2+1]]?t[i*2]:t[i*2+1];
printf("%d\n",calc(0,n-1,0));
return 0;
}
|
448
|
D
|
Multiplication Table
|
Bizon the Champion isn't just charming, he also is very smart.
While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an $n × m$ multiplication table, where the element on the intersection of the $i$-th row and $j$-th column equals $i·j$ (the rows and columns of the table are numbered starting from 1). Then he was asked: what number in the table is the $k$-th largest number? Bizon the Champion always answered correctly and immediately. Can you repeat his success?
Consider the given multiplication table. If you write out all $n·m$ numbers from the table in the non-decreasing order, then the $k$-th number you write out is called the $k$-th largest number.
|
Solution is binary search by answer. We need to find largest $x$ such that amount of numbers from table, least than $x$, is strictly less than $k$. To calculate this count we sum counts from rows. In $i$ th row there will be $m i n({\frac{x-1}{i}},m)$. Total complexity is $O(nlog(nm))$.
|
[
"binary search",
"brute force"
] | 1,800
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e6+6;
ll f(ll x, int n, int m){
ll res = 0;
--x;
for(int i=1;i<=n;++i) res+=min((ll)m, x/i);
return res;
}
int main(){
//freopen("input.txt","r",stdin);// freopen("output.txt","w",stdout);
int n, m;
cin>>n>>m;
ll k;
cin>>k;
ll l = 1, r = 1LL*n*m+1;
while(l<r){
ll x = (l+r)>>1;
if(f(x,n,m)<k) l = x+1; else r = x;
}
cout<<l-1<<endl;
return 0;
}
|
448
|
E
|
Divisors
|
Bizon the Champion isn't just friendly, he also is a rigorous coder.
Let's define function $f(a)$, where $a$ is a sequence of integers. Function $f(a)$ returns the following sequence: first all divisors of $a_{1}$ go in the increasing order, then all divisors of $a_{2}$ go in the increasing order, and so on till the last element of sequence $a$. For example, $f([2, 9, 1]) = [1, 2, 1, 3, 9, 1]$.
Let's determine the sequence $X_{i}$, for integer $i$ $(i ≥ 0)$: $X_{0} = [X]$ ($[X]$ is a sequence consisting of a single number $X$), $X_{i} = f(X_{i - 1})$ $(i > 0)$. For example, at $X = 6$ we get $X_{0} = [6]$, $X_{1} = [1, 2, 3, 6]$, $X_{2} = [1, 1, 2, 1, 3, 1, 2, 3, 6]$.
Given the numbers $X$ and $k$, find the sequence $X_{k}$. As the answer can be rather large, find only the first $10^{5}$ elements of this sequence.
|
Learn how to transform $X_{i}$ into $X_{i + 1}$. For this we need to concatenate lists of divisors for all elements of $X_{i}$. To do this efficiently, precalculate divisors of $X$ (because for every $i$ $X_{i}$ consist of its divisors). It can be done by well-known method with $O({\sqrt{X}})$ complexity. How to calculate divisors of divisors? Need to know that for the given constrains for $X$ maximum number of divisors $D(X)$ will be 6720 (in the number 963761198400), so divisors of divisors can be calculated in $O(D^{2}(X))$ time. With this lists we can transform $X_{i}$ into $X_{i + 1}$ in $O(N)$ time, were $N = 10^{5}$ - is the limit of numbers in output. Now learn how to transform $X_{i}$ into $X_{2i}$. What says $X_{i}$? Besides what would be $X$ after $i$ steps, it can tell where goes everyone divisor of $X$ after $i - 1$ steps. Actually, $X_{i}$ is concatenation of all $Y_{i - 1}$, where $Y$ is divisor of $X$. For example, $10_{3} = [1, 1, 1, 2, 1, 1, 5, 1, 1, 2, 1, 5, 1, 2, 5, 10] = [1] + [1, 1, 2] + [1, 1, 5] + [1, 1, 2, 1, 5, 1, 2, 5, 10] = 1_{2} + 2_{2} + 5_{2} + 10_{2}$. How to know which segment corresponds for some $Y$? Lets $pos(Y)$ be the first index of $Y$ in $X_{i}$. Then needed segment starts from $pos(prev(Y)) + 1$ and ends in $pos(Y)$, where $prev(Y)$ is previous divisor before $Y$ in sorted list of divisors. So, to make $X_{2i}$ from $X_{i}$ we need to know where goes every element from $X_{i}$ after $i$ steps. We know all its divisors - it is one step, and for every divisor we know where it goes after $i - 1$ step. Thus, we again need to concatenate some segments in correct order. It also can be done in $O(N)$ time. How to find now $X_{k}$ for every $k$? The method is similar as fast exponentiation: $X_{k} = [X]$ when $k = 0$, if $k$ is odd then transform $X_{k - 1}$ to $X_{k}$, if $k$ is even then transform $X_{k / 2}$ to $X_{k}$. This method takes $O(logk)$ iterations. And one small trick: obviously that for $X > 1$ $X_{k}$ starts from $k$ ones, so $k$ can be limited by $N$. Total complexity of solution is $O(\sqrt{X}+D^{2}(X)+N l o q(m i n(N,k)))$.
|
[
"brute force",
"dfs and similar",
"implementation",
"number theory"
] | 2,200
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cmath>
#include <memory.h>
using namespace std;
typedef long long ll;
const int N = 1e5;
vector<ll> d;
vector<ll> g[N];
vector<int> gi[N];
ll x;
vector<int> f(int k){
if(k==0) return vector<int>(1,d.size()-1);
vector<int> res;
if(k&1){
vector<int> v = f(k-1);
for(int i=0;i<v.size();++i)
for(int j=0;res.size()<N && j<gi[v[i]].size();++j) res.push_back(gi[v[i]][j]);
}else{
vector<int> v = f(k>>1);
vector<int> pos(d.size());
for(int i=0, j=0;i<v.size();++i) if(v[i]==j) pos[j++] = i;
for(int i=0;i<v.size();++i)
for(int j=0;res.size()<N && j<gi[v[i]].size();++j){
int y = gi[v[i]][j];
int l = y ? pos[y-1]+1 : 0;
int r = pos[y];
for(int k=l;res.size()<N && k<=r; ++k) res.push_back(v[k]);
}
}
return res;
}
vector<ll> solve(int k){
vector<int> v = f(k);
vector<ll> res(v.size());
for(int i=0;i<v.size();++i) res[i] = d[v[i]];
return res;
}
int main(){
//freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);
cin>>x;
for(ll i=1; i*i<=x; ++i) if(x%i==0){
d.push_back(i);
if(i*i!=x) d.push_back(x/i);
}
sort(d.begin(), d.end());
int cnt = 0;
for(int i=0;i<d.size();++i){
for(int j=0;j<=i;++j) if(d[i]%d[j]==0){
g[i].push_back(d[j]);
gi[i].push_back(j);
}
cnt+=g[i].size();
}
ll kk;
cin>>kk;
int k = min(kk, (ll)N);
vector<ll> r2 = solve(k);
for(int i=0;i<r2.size();++i) printf("%I64d ",r2[i]); printf("\n");
return 0;
}
|
449
|
A
|
Jzzhu and Chocolate
|
Jzzhu has a big rectangular chocolate bar that consists of $n × m$ unit squares. He wants to cut this bar exactly $k$ times. Each cut must meet the following requirements:
- each cut should be straight (horizontal or vertical);
- each cut should go along edges of unit squares (it is prohibited to divide any unit chocolate square with cut);
- each cut should go inside the whole chocolate bar, and all cuts must be distinct.
The picture below shows a possible way to cut a $5 × 6$ chocolate for $5$ times.
Imagine Jzzhu have made $k$ cuts and the big chocolate is splitted into several pieces. Consider the smallest (by area) piece of the chocolate, Jzzhu wants this piece to be as large as possible. What is the maximum possible area of smallest piece he can get with exactly $k$ cuts? The area of a chocolate piece is the number of unit squares in it.
|
We assume that $n \le m$ (if $n > m$, we can simply swap $n$ and $m$). If we finally cut the chocolate into $x$ rows and $y$ columns $(1 \le x \le n, 1 \le y \le m, x + y = k + 2)$, we should maximize the narrowest row and maximize the narrowest column, so the answer will be $floor(n / x) * floor(m / y)$. There are two algorithms to find the optimal $(x, y)$. Notice that if $x * y$ is smaller, the answer usually will be better. Then we can find that if $k < n$, the optimal $(x, y)$ can only be ${x = 1, y = k + 1}$ or ${x = k + 1, y = 1}$. If $n \le k < m$, the optimal $(x, y)$ can only be ${x = 1, y = k + 1}$. If $m \le k \le n + m - 2$, the optimal $(x, y)$ can only be ${x = k + 2 - m, y = m}$, because let $t = m - n$, $n / (k + 2 - m) \ge (n + t) / (k + 2 - m + t) \ge 1$. $floor(n / x)$ has at most $2{\sqrt{n}}$ values, so we can enum it and choose the maximum $x$ for each value.
|
[
"greedy",
"math"
] | 1,700
| null |
449
|
B
|
Jzzhu and Cities
|
Jzzhu is the president of country A. There are $n$ cities numbered from $1$ to $n$ in his country. City $1$ is the capital of A. Also there are $m$ roads connecting the cities. One can go from city $u_{i}$ to $v_{i}$ (and vise versa) using the $i$-th road, the length of this road is $x_{i}$. Finally, there are $k$ train routes in the country. One can use the $i$-th train route to go from capital of the country to city $s_{i}$ (and vise versa), the length of this route is $y_{i}$.
Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.
|
We consider a train route $(1, v)$ as an undirected deletable edge $(1, v)$. Let $dist(u)$ be the shortest path between $1$ and $u$. We add all of the edges $(u, v)$ weighted $w$ where $dist(u) + w = dist(v)$ into a new directed graph. A deletable edge $(1, v)$ can be deleted only if it isn't in the new graph or the in-degree of $v$ in the new graph is more than $1$, because the connectivity of the new graph won't be changed after deleting these edges. Notice that you should subtract one from the in-degree of $v$ after you delete an edge $(1, v)$.
|
[
"graphs",
"greedy",
"shortest paths"
] | 2,000
| null |
449
|
C
|
Jzzhu and Apples
|
Jzzhu has picked $n$ apples from his big apple tree. All the apples are numbered from $1$ to $n$. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.
Jzzhu wonders how to get the maximum possible number of groups. Can you help him?
|
Firstly, we should notice that $1$ and the primes larger than $N / 2$ can not be matched anyway, so we ignore these numbers. Let's consider each prime $P$ where $2 < P \le N / 2$. For each prime $P$, we find all of the numbers which are unmatched and have a divisor $P$. Let $M$ be the count of those numbers we found. If $M$ is even, then we can match those numbers perfectly. Otherwise, we throw the number $2P$ and the remaining numbers can be matched perfectly. Finally, only even numbers may be unmatched and we can match them in any way.
|
[
"constructive algorithms",
"number theory"
] | 2,500
| null |
449
|
D
|
Jzzhu and Numbers
|
Jzzhu have $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. We will call a sequence of indexes $i_{1}, i_{2}, ..., i_{k}$ $(1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ n)$ a group of size $k$.
Jzzhu wonders, how many groups exists such that $a_{i1}$ & $a_{i2}$ & ... & $a_{ik} = 0$ $(1 ≤ k ≤ n)$? Help him and print this number modulo $1000000007$ $(10^{9} + 7)$. Operation $x$ & $y$ denotes bitwise AND operation of two numbers.
|
Firstly, we can use inclusion-exclusion principle in this problem. Let $f(x)$ be the count of number $i$ where $A_{i}&x = x$. Let $g(x)$ be the number of $1$ in the binary respresentation of $x$. Then the answer equals to $\textstyle\sum_{x=0}^{20}(-1)^{g(x)}2^{f(x)}$. Now the task is to calculate $f(x)$ for every integer $x$ between $0$ and $2^{20}$. Let $f_{k}(x)$ be the count of number $i$ where $Y_{0}&X_{0} = X_{0}$ and $X_{1} = Y_{1}$ (they are defined below). We divide $x$ and $A_{i}$ into two parts, the first $k$ binary bits and the other $20 - k$ binary bits. Let $X_{0}$ be the first part of $x$ and $X_{1}$ be the second part of $x$. Let $Y_{0}$ be the first part of $A_{i}$ and $Y_{1}$ be the second part of $A_{i}$. We can calculate $f_{k}(x)$ in $O(1)$: $f_{k}(x)={\left\{f_{k-1}(x)+f_{k-1}(x+2^{k}){\quad}{\mathrm{the~k}\!\cdot\!\mathrm{th~binary~bit~of~x~equals~to~}}0}$ The problem can be solved in $O(n * 2^{n})$ now ($n = 20$ in this problem).
|
[
"bitmasks",
"combinatorics",
"dp"
] | 2,400
| null |
449
|
E
|
Jzzhu and Squares
|
Jzzhu has two integers, $n$ and $m$. He calls an integer point $(x, y)$ of a plane special if $0 ≤ x ≤ n$ and $0 ≤ y ≤ m$. Jzzhu defines a unit square as a square with corners at points $(x, y)$, $(x + 1, y)$, $(x + 1, y + 1)$, $(x, y + 1)$, where $x$ and $y$ are some integers.
Let's look at all the squares (their sides not necessarily parallel to the coordinate axes) with corners at the special points. For each such square Jzzhu paints a dot in every unit square that is fully inside it. After that some unit squares can contain several dots. Now Jzzhu wonders, how many dots he has painted on the plane. Find this number modulo $1000000007$ $(10^{9} + 7)$.
|
Consider there is only one query. Let me descripe the picture above. A grid-square can be exactly contained by a bigger square which coincide with grid lines. Let $L$ be the length of a side of the bigger square. Let $i$ be the minimum distance between a vertice of the grid-square and a vertice of the bigger square. Let $f(L, i)$ be the number of cells which are fully contained by the grid-square. We can divide a grid-square into four right triangles and a center square. For each right triangle, the number of cells which are crossed by an edge of the triangle is $L - gcd(i, L)$. Then, the number of cells which are fully contained by the triangle is $[i(L - i) - L + gcd(i, L)] / 2$. $f(L, i) = (L - 2i)^{2} + 2[i(L - i) - L + gcd(i, L)] = L^{2} - 2iL + 2i^{2} - 2L + 2gcd(i, L)$ Firstly, we enum $L$ from $1$ to $min(N, M)$. Then the task is to calculate $(N-L+1)*(M-L+1)*\sum_{i=1}^{L}f(L,i)$. $\textstyle\sum_{i=1}^{L}g c d(i,L)$ can be calculated by the following steps: Enum all of the divisor $k$ of $L$ and the task is to calculate the count of $i$ where $gcd(i, L) = k$. The count of $i$ where $gcd(i, L) = k$ equals to $ \phi (L / k)$. Finally, $\textstyle\sum_{i=1}^{L}f(L,i)=L(L+1)(2L+1)/3-3L^{2}+2\sum_{i=1}^{L}g c d(i,L)$. If there are multiple queries, we can calculate the prefix sum of $\textstyle\sum_{i=1}^{L}f(L,i)$, $L\sum_{i=1}^{L}f(L,i)$ and $L^{2}\sum_{i=1}^{L}f(L,i)$, then we can answer each query in $O(1)$.
|
[
"dp",
"math",
"number theory"
] | 2,900
| null |
450
|
A
|
Jzzhu and Children
|
There are $n$ children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from $1$ to $n$. The $i$-th child wants to get at least $a_{i}$ candies.
Jzzhu asks children to line up. Initially, the $i$-th child stands at the $i$-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:
- Give $m$ candies to the first child of the line.
- If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home.
- Repeat the first two steps while the line is not empty.
Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?
|
You can simply simulate it or find the last maximum $ceil(a_{i} / m)$.
|
[
"implementation"
] | 1,000
| null |
450
|
B
|
Jzzhu and Sequences
|
Jzzhu has invented a kind of sequences, they meet the following property:
\[
f_{1}=x;\ f_{2}=y;\ \forall\ i\ (i\geq2),f_{i}=f_{i-1}+f_{i+1}.
\]
You are given $x$ and $y$, please calculate $f_{n}$ modulo $1000000007$ $(10^{9} + 7)$.
|
We can easily find that every $6$ numbers are the same. It's like ${x, y, y - x, - x, - y, x - y, x, y, y - x, ...}$.
|
[
"implementation",
"math"
] | 1,300
| null |
451
|
A
|
Game With Sticks
|
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of $n$ horizontal and $m$ vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid shown below, $n = 3$ and $m = 3$. There are $n + m = 6$ sticks in total (horizontal sticks are shown in red and vertical sticks are shown in green). There are $n·m = 9$ intersection points, numbered from $1$ to $9$.
The rules of the game are very simple. The players move in turns. Akshat won gold, so he makes the first move. During his/her move, a player must choose any remaining intersection point and remove from the grid all sticks which pass through this point. A player will lose the game if he/she cannot make a move (i.e. there are no intersection points remaining on the grid at his/her move).
Assume that both players play optimally. Who will win the game?
|
From a grid of size $n * m$, if we remove an intersection point, then the grid after removing the sticks passing through it, will of size $n - 1$, $m - 1$. Notice when the grid consists of a single horizontal stick and m vertical sticks, If we pick any intersection point, then the updated grid will be only made of vertical sticks. You can see that there is no intersection point in the grid now. So $ans(n, m) = ans(n - 1, m - 1)$ ^ $1.$ $ans(1, * ) = 1$ $ans( * , 1) = 1$ So we can notice that answer will depend on the parity of $minimum(m, n)$. You can prove it using the previous equations. You can also check this by seeing the pattern. So finally if $min(n, m)$ is odd, then Akshat will win. Otherwise Malvika will win. You can also observe that "players will play optimally" is useless in this case. Complexity : $O$(1)
|
[
"implementation"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
if (n > m) {
swap(n, m);
}
if (n % 2 == 0) {
cout << "Malvika" << endl;
} else {
cout << "Akshat" << endl;
}
return 0;
}
|
451
|
B
|
Sort the Array
|
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array $a$ consisting of $n$ \textbf{distinct} integers.
Unfortunately, the size of $a$ is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array $a$ (in increasing order) by reversing \textbf{exactly one} segment of $a$? See definitions of segment and reversing in the notes.
|
Note that if from a given sorted array, if reverse a segment, then the remaining array will be arranged in following way. First increasing sequence, then decreasing, then again increasing. You can find the first position where the sequences start decreasing from the beginning. Call it $L$. You can find the first position where the sequences start increasing from the end. Call it $R$. Now we just need to reverse the segment between $a[L]$ to $a[R]$. Here is outline of my solution which is easy to implement. First I map larger numbers to numbers strictly in the range 1, n. As all the numbers are distinct, no two numbers in the mapping will be equal too. Let us define $L$ to be smallest index such that $A[i]! = i$. Let us also define $R$ to be largest index such that $A[i]! = i$. Note that if there is no such L and R, it means that array is sorted already. So answer will be "yes", we can simply reverse any of the 1 length consecutive segment. Otherwise we will simply reverse the array from $[L, R]$. After the reversal, we will check whether the array is sorted or not. Complexity: $O(nlogn)$
|
[
"implementation",
"sortings"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
const int N = (int) 1e5 + 5;
int a[N], b[N];
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
b[i] = a[i];
}
map<int, int> mp;
sort(b, b + n);
for (int i = 0; i < n; i++) {
mp[b[i]] = i;
}
for (int i = 0; i < n; i++) {
a[i] = mp[a[i]];
}
int L = -1;
for (int i = 0; i < n; i++) {
if (a[i] != i) {
L = i;
break;
}
}
int R = -1;
for (int i = n - 1; i >= 0; i--) {
if (a[i] != i) {
R = i;
break;
}
}
if (L == -1 || R == -1) {
cout << "yes" << endl;
cout << 1 << " " << 1 << endl;
} else {
reverse(a + L, a + R + 1);
int ok = true;
for (int i = 0; i < n; i++) {
if (a[i] != i) {
ok = false;
}
}
if (ok) {
cout << "yes" << endl;
cout << L + 1 << " " << R + 1 << endl;
} else {
cout << "no" << endl;
}
}
return 0;
}
|
451
|
C
|
Predict Outcome of the Game
|
There are $n$ games in a football tournament. Three teams are participating in it. Currently $k$ games had already been played.
You are an avid football fan, but recently you missed the whole $k$ games. Fortunately, you remember a guess of your friend for these $k$ games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be $d_{1}$ and that of between second and third team will be $d_{2}$.
You don't want any of team win the tournament, that is each team should have the same number of wins after $n$ games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?
Note that outcome of a match can not be a draw, it has to be either win or loss.
|
Let $x_{1}$ be number of wins of first team in the first k games. Let $x_{2}$ be number of wins of second team in the first k games. Let $x_{3}$ be number of wins of third team in the first k games. Note that $x_{1} + x_{2} + x_{3} = k$ ---(1) $|x_{1} - x_{2}| = d_{1}.$ - (a) $|x_{2} - x_{3}| = d_{2}.$ - (b) Note that |x| can be x and -x depending on the sign of x. Case 1: Assume that $x_{1} > x_{2}$ and $x_{2} > x_{3}$. $x_{1} - x_{2} = d_{1}$ ---(2) $x_{2} - x_{3} = d_{2}$ ---(3) Adding 1 and 2, we get $2x_{1} + x_{3} = d_{1} + k$ --(4) Adding 2 and 3, we get $x_{1} - x_{3} = d_{1} + d_{2}$ ---(5). Now solve (4) and (5), we will get values of $x_{1}$ and $x_{3}$. By those values, compute value of $x_{2}$. Now we should check the constraints that $x_{1} \ge x_{2}$ and $x_{2} \ge 3$. Now comes the most important part. Number of wins at the end of each team should be $n / 3$. So if $n$ is not divisible by 3, then our answer will be definitely "no". Note that if all of the $x_{1}, x_{2}, x_{3}$ are $ \le n / 3$, then we can have the remaining matches in such a way that final numbers of wins of each team should be equal. Now you have to take 4 such cases. Implementing such cases in 4 if-else statements could incur errors in implementation. You can check my code to understand a simple way to implement it. I will explain idea of my code briefly, basically equation (a) and (b) can be opened with either positive or negative sign due to modulus. So if our sign is negative we will change $d_{1}$ to be $- d_{1}$. So if we solve a single equation and replace $d_{1}$ by $- d_{1}$, we can get solution for the second case. All the cases can be dealt in such way. Please see my code for more details. Complexity: $O$(1) per test case.
|
[
"brute force",
"implementation",
"math"
] | 1,700
|
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int solveFaster(LL n, LL k, LL d1, LL d2) {
if (n % 3 != 0) {
return 0;
}
for (int sign1 = -1; sign1 <= 1; sign1++) {
for (int sign2 = -1; sign2 <= 1; sign2++) {
if (sign1 == 0 || sign2 == 0) {
continue;
}
LL D1 = d1 * sign1;
LL D2 = d2 * sign2;
LL x2 = (k - D1 + D2) / 3;
if ((k - D1 + D2) % 3 != 0) {
continue;
}
if (x2 >= 0 && x2 <= k) {
LL x1 = D1 + x2;
LL x3 = x2 - D2;
if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {
if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {
assert(abs(x1 - x2) == d1);
assert(abs(x2 - x3) == d2);
return true;
}
}
}
}
}
return false;
}
int main() {
int T;
cin >> T;
while (T--) {
LL n, k, d1, d2;
cin >> n >> k >> d1 >> d2;
int ans = solveFaster(n, k, d1, d2);
if (ans == 1)
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
}
|
451
|
D
|
Count Good Substrings
|
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
- the number of good substrings of even length;
- the number of good substrings of odd length.
|
Merging Step: We have to convert string like "aaaabbbaabaaa" into "ababa". Important Observation A substring made of the string will be a "good" palindrome if their starting and ending characters are same. If the starting and ending characters are same, then the middle characters after merging will be alternating between 'a' and 'b'. eg. "abaa" is not a palindrome, but it is a good palindrome. After merging step it becomes "aba". Note that in the string left after merging, the consecutive characters will alternate between 'a' and 'b'. So if we are currently at the $i^{th}$ character, then we can have to simply check how many positions we have encountered upto now having the same character as that of $i^{th}$. For counting even and odd separately, we can make count of a's and b's at even and odd positions. So if we are at $i^{th}$ position, for counting even good palindromes, you just need to add count of number of characters a's at odd position. For counting odd good palindromes, you just need to add count of number of characters a's at even position. Complexity: $O$(n) where $n$ is length of string $s$.
|
[
"math"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
pair<LL, LL> solve(string s)
{
LL ansEven = 0, ansOdd = 0;
int cntEven[2], cntOdd[2];
cntEven[0] = cntEven[1] = cntOdd[0] = cntOdd[1] = 0;
for (int i = 0; i < s.size(); i++)
{
ansOdd++;
int id = s[i] - 'a';
if (i % 2 == 0)
{
ansOdd += cntEven[id];
ansEven += cntOdd[id];
cntEven[id]++;
}
else
{
ansOdd += cntOdd[id];
ansEven += cntEven[id];
cntOdd[id]++;
}
}
return make_pair(ansEven, ansOdd);
}
int main()
{
srand(time(NULL));
string s;
cin >> s;
pair<long long, long long> ans = solve(s);
cout << ans.first << " " << ans.second << endl;
return 0;
}
|
451
|
E
|
Devu and Flowers
|
Devu wants to decorate his garden with flowers. He has purchased $n$ boxes, where the $i$-th box contains $f_{i}$ flowers. All flowers in a single box are of the same color (hence they are indistinguishable). Also, no two boxes have flowers of the same color.
Now Devu wants to select \textbf{exactly} $s$ flowers from the boxes to decorate his garden. Devu would like to know, in how many different ways can he select the flowers from each box? Since this number may be very large, he asks you to find the number modulo $(10^{9} + 7)$.
Devu considers two ways different if there is at least one box from which different number of flowers are selected in these two ways.
|
The number of ways to choose $N$ items out of $R$ groups where each item in a group is identical is equal to the number of integral solutions to $x_{1} + x_{2} + x_{3}...x_{R} = N$, where $0 \le x_{i} \le L_{i}$, where $L_{i}$ is the number of items in $i^{th}$ group. Number of integral solutions are coefficient of $x^{N}$ in [Product of $(1 + x + x * x + ...x^{Li}$) over all $i$]. You need to find coefficient of $x^{s}$ in $(1 + x + x^{2} + x^{3} + + ..x^{f1}) * * * (1 + x + x^{2} + x^{3} + + ..x^{fn})$. Using sum of Geometric progression we can say that $(1 + x + x^{2} + x^{3} + + ..x^{f1}) = (1 - x^{(f1 + 1)}) / (1 - x)$. Substituting in the expression, we get $(1 - x^{(f1 + 1))} / (1 - x) * * * (1 - x^{(fn + 1))} / (1 - x).$ = $(1 - x^{(f1 + 1))} * .. * (1 - x^{(fn + 1))} * (1 - x)^{( - n)}.$ Now we can find $x^{s}$ in $(1 - x)^{ - n}$ easily. It is $\left(^{(n+s-1)}\right)$. You can have a look at following link. to understand it better. So now as $s$ is large, we can not afford to iterate over $s$. But $n$ is small, we notice that $(1 - x^{(f1 + 1))} * .. * (1 - x^{(fn + 1))}$ can have at most $2^{n}$ terms. So we will simply find all those terms, they can be very easily computed by maintaining a vector<pair<int, int> > containing pairs of coefficients and their corresponding powers. You can write a recursive function for doing this. How to find $\binom{(n+s-1)}{(s)}$ % p. As $n + s - 1$ is large and s is very small. You can use lucas's theorem. If you understand lucas's theorem, you can note that we simply have to compute $\binom{(n+s-1)\mathcal{V}_{\mathrm{c}}p}{s\mathcal{V}_{\mathrm{c}}p}\Biggr)$. Complexity: $O(n * 2^{n})$. Another solution based on inclusion exclusion principle.
|
[
"bitmasks",
"combinatorics",
"number theory"
] | 2,300
|
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++)
#define snuke(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)
const long long mod = (long long) (1e9 + 7);
int n;
LL f[22], s, inv[55];
LL nCr(LL n, LL r) {
if (r > n) return 0;
if (n - r < r) r = n - r;
n %= mod;
LL ans = 1;
REP(i, r) {
ans = (ans * (n - i)) % mod;
ans = (ans * inv[i + 1]) % mod;
}
return ans;
}
LL modpow(LL a, LL b, LL mod) {
LL res = 1;
while (b) {
if (b & 1) res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
void pre() {
for (int i = 1; i <= 50; i++) {
inv[i] = modpow(i, mod - 2, mod);
}
}
int main() {
pre();
cin>>n>>s;
REP(i,n) cin>>f[i];
LL ans = 0;
REP(mask,(1<<n)){
LL x = s;
int tot = 0;
REP(i,n){
if (mask & (1<<i)) {
x -= (f[i] + 1);
tot++;
}
}
if (x < 0) continue;
LL temp = nCr(x + n - 1, n - 1);
if (tot & 1) temp = - temp;
ans = (ans + temp) % mod;
if (ans < 0) ans += mod;
}
cout << ans << endl;
return 0;
}
|
452
|
B
|
4-point polyline
|
You are given a rectangular grid of lattice points from $(0, 0)$ to $(n, m)$ inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.
A polyline defined by points $p_{1}, p_{2}, p_{3}, p_{4}$ consists of the line segments $p_{1} p_{2}, p_{2} p_{3}, p_{3} p_{4}$, and its length is the sum of the lengths of the individual line segments.
|
The critical observation in this problem is that the points will be at the corners or very close to the corners. After that one simple solution would be to generate a set of all the points that are within 4 cells from some corner, and consider all quadruplets of points from that set.
|
[
"brute force",
"constructive algorithms",
"geometry",
"trees"
] | 1,800
| null |
452
|
C
|
Magic Trick
|
Alex enjoys performing magic tricks. He has a trick that requires a deck of $n$ cards. He has $m$ identical decks of $n$ different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs $n$ cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards.
The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful.
You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case.
|
When the magician reveals the card, he has $\textstyle{\frac{1}{k}}$ chance to reveal the same exact card that you have chosen. With the remaining $\frac{k{\mathrm{k}}-1}{k}$ chance he will reveal some other card. Since all the cards in all $m$ decks are equally likely to be in the $n$ cards that he uses to perform the trick, he is equally likely to reveal any card among the $n \times m - 1$ cards (-1 for the card that you have chosen, which we assume he has not revealed). There are only $m - 1$ cards that can be revealed that have the same value as the card you chose but are not the card you chose. Thus, the resulting probability is ${\frac{1}{k}}+{\frac{k-1}{k}}\times{\frac{m-1}{n\times m-1}}$
|
[
"combinatorics",
"math",
"probabilities"
] | 2,100
| null |
452
|
D
|
Washer, Dryer, Folder
|
You have $k$ pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has $n_{1}$ washing machines, $n_{2}$ drying machines and $n_{3}$ folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.
It takes $t_{1}$ minutes to wash one piece of laundry in a washing machine, $t_{2}$ minutes to dry it in a drying machine, and $t_{3}$ minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.
|
One way to solve this problem is to maintain three deques, one per machine type, each one containing moments of time when the machines of this type will be available in increasing order. Originally each deck has as many zeroes, as many machines of that type are available. For each piece of laundry, see the earliest moment of time when each of the three machines will be available, and chose the time to put it in a washer in such a way, that there will be no delay when you move it to the dryer and to the folder. Remove the first elements from each of the deques, and push back moments of time when the piece of laundry you are processing is washed, dried and folded correspondingly. It can be shown that by doing that you will maintain all the deques sorted.
|
[
"greedy",
"implementation"
] | 1,900
| null |
452
|
E
|
Three strings
|
You are given three strings $(s_{1}, s_{2}, s_{3})$. For each integer $l$ $(1 ≤ l ≤ min(|s_{1}|, |s_{2}|, |s_{3}|)$ you need to find how many triples ($i_{1}, i_{2}, i_{3}$) exist such that three strings $s_{k}[i_{k}... i_{k} + l - 1]$ $(k = 1, 2, 3)$ are pairwise equal. Print all found numbers modulo $1000000007 (10^{9} + 7)$.
See notes if you are not sure about some of the denotions used in the statement.
|
This problem requires one to use one of the datastructures, such as suffix array, suffix tree or suffix automata. The easiest solution uses a compressed suffix tree. Build one suffix tree on all three strings. For simplicity add some non-alphabetic character at the end of each string. For every node in the tree store how many times the corresponding suffix occurs in each string. Then traverse the tree once. If the tree had no shortcuts, for every node that is $a$ characters away from the root you would have increased the answer for $a$ by the product of numbers of occurrences of the suffix in each of the strings. Since you do have shortcuts, you need to update the answer for all the lengths from $a$ to $b$, where $a$ and $b$ are the distances of two ends of the shortcut from the root. One way to do it with constant time updates and linear time to print all the answers is the following. If the array of answers is $v$, then instead of computing $v$ we can compute the array of differences $p$, such that $p_{i} = v_{i} - v_{i - 1}$. This way when you traverse the shortcut, rather than adding some value at all the positions from $a$ to $b$, you only need to add that value at position $a$, and subtract it at position $b$. When $p$ is computed, it is easy to restore $v$ in one pass.
|
[
"data structures",
"dsu",
"string suffix structures",
"strings"
] | 2,400
| null |
452
|
F
|
Permutation
|
You are given a permutation of numbers from $1$ to $n$. Determine whether there's a pair of integers $a, b$ $(1 ≤ a, b ≤ n; a ≠ b)$ such that the element $\textstyle{\frac{(a+b)}{2}}$ (note, that it is usual division, not integer one) is between $a$ and $b$ in this permutation.
|
There are at least two different ways to solve this problem First way is to notice that almost all the permutations have such numbers $a$ and $b$. Consider solving the opposite problem: given $n$, build a permutation such that no subsequence of length 3 forms an arithmetic progression. One way to do that is to solve similar problem recursively for odd and even elements and concatenate the answer, i.e. solve it for $\frac{n t}{2}$, and then form the answer for $n$ as all the elements of the solution for $\frac{n t}{2}$ multiplied by two, followed by those elements multiplied by two minus one. This way we first place all the even numbers of the sequence, and then all the odd or vice versa. Now one observation that can be made is that all the permutations that don't have a subsequence of length 3 that is an arithmetic progression are similar, with may be several elements in the middle being mixed up. As a matter of fact, it can be proven that the farthest distance an odd number can have from the odd half (or even number can have from the even part) is 6. With this knowledge we can build simple divide and conquer solution. If $n < = 20$, use brute force solution, otherwise, if the first and the last elements have the same remainder after division by two, then the answer is YES, otherwise, assuming without loss of generality that the first element is odd, if the distance from the first even element to the last odd element is more than 12, then the answer is YES, otherwise one can just recursively check all the odd elements separately, all the even elements separately, and then consider triplets of numbers, where one number is either in the odd or even part, and two numbers are among the at most 12 elements in the middle. This solution works in $nlog(n)$ time. Another approach, that does not rely on the observation above, is to consider elements one by one, from left to right, maintaining a bitmask of all the numbers we've seen so far. If the current element we are considering is $a$, then for every element $a - k$ that we saw, if we didn't see $a + k$ (assuming both $a - k$ and $a + k$ are between $0$ and $n - 1$), then the answer is YES. Note that $a - k$ was seen and $a + k$ was not seen for some $k$ if and only if the bitmask is not a palindrome with a center at $a$. To verify if it is a palindrome or not one can use polynomial hashes, making the complexity to be $n \times log(n)$.
|
[
"data structures",
"divide and conquer",
"hashing"
] | 2,700
| null |
453
|
A
|
Little Pony and Expected Maximum
|
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.
The dice has $m$ faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the $m$-th face contains $m$ dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability $\textstyle{\frac{1}{m}}$. Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice $n$ times.
|
Take $m$ = 6, $n$ = 2 as a instance. 6 6 6 6 6 6 5 5 5 5 5 6 4 4 4 4 5 6 3 3 3 4 5 6 2 2 3 4 5 6 1 2 3 4 5 6Enumerate the maximum number, the distribution will be a $n$-dimensional super-cube with $m$-length-side. Each layer will be a large cube minus a smaller cube. So we have: $\textstyle\sum_{i=1}^{m}i(i^{n}-(i-1)^{n})/m^{n}$Calculate $i^{n}$ may cause overflow, we could move the divisor into the sum and calculate $(i / m)^{n}$ instead.
|
[
"probabilities"
] | 1,600
| null |
453
|
B
|
Little Pony and Harmony Chest
|
Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony.
A sequence of positive integers $b_{i}$ is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmony sequence $b_{i}$ which minimizes the following expression:
\[
\sum_{i=1}^{n}|a_{i}-b_{i}|.
\]
You are given sequence $a_{i}$, help Princess Twilight to find the key.
|
Since {1, 1 $...$, 1} is a pairwise coprime sequence, the maximum element of $b_{i}$ can never greater then $2mx - 1$. Here $mx$ is the maximum elements in $a_{i}$. So what we need consider is the first a few prime factors. It is not hard to use bitmask-dp to solve this: for (int i = 1 ; i <= n ; i ++) { for (int k = 1 ; k < 60 ; k ++) { int x = (~fact[k]) & ((1 << 17) - 1); for (int s = x ; ; s = (s - 1) & x) { if (dp[i - 1][s] + abs(a[i] - k) < dp[i][s | fact[k]]){ dp[i][s | fact[k]] = dp[i-1][s] + abs(a[i]-k); } if (s == 0) break; } } }Here dp[i][s]: means the first $i$ items of the sequence, and the prime factor have already existed. And fact[k]: means the prime factor set of number $k$.
|
[
"bitmasks",
"brute force",
"dp"
] | 2,000
| null |
453
|
C
|
Little Pony and Summer Sun Celebration
|
Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration.
Twilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information?
Ponyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than $4n$ places.
|
There is no solution if there is more than 1 connected component which have odd node (because we can't move between two component), otherwise it is always solvable. This fact is not obvious, let's focus on one component. You can select any node to start, denoted it as $r$ (root). Start from $r$, you can go to any other odd node then back. Each time you can eliminate one odd node. After that, if $r$ itself is odd, you can simply delete the first or last element in your path (it must be $r$). The only spot of the above method is the size of the path can been large as $O(n^{2})$. We need a more local observation. Let's check the following dfs() function: void dfs(int u = r, int p = -1){ vis[u] = true; add_to_path(u); for_each(v in adj[u]) if (!vis[v]){ dfs(v, u); add_to_path(u); } if (odd[u] && p != -1){ add_to_path(p); add_to_path(u); } }This dfs() maintain the following loop invariant: before we leave a node $u$, we clear all odd node in the sub-tree rooted at $u$ as well as $u$ itself. The only $u$ can break the invariant is the root itself. So after dfs(), we use O(1) time to check weather root is still a odd node, if yes, delete the first or last element of the path (it must be $r$). After that, all the node will been clear, each node can involve at most 4 items in the path. So the size of the path will less than or equal to $4n$. Thus the overall complexity is $O(n + m)$.
|
[
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,200
| null |
453
|
D
|
Little Pony and Elements of Harmony
|
The Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with $n$ vertices labeled from 0 to $n - 1$, where $n$ is a power of two, equal to $2^{m}$.
The energy in Elements of Harmony is in constant movement. According to the ancient book, the energy of vertex $u$ in time $i$ $(e_{i}[u])$ equals to:
\[
e_{i}[u]=\sum_{n}e_{i-1}[v]\cdot b[f(u,v)].
\]
Here $b[]$ is the transformation coefficient — an array of $m + 1$ integers and $f(u, v)$ is the number of ones in the binary representation of number $(u xor v)$.
Given the transformation coefficient and the energy distribution at time 0 $(e_{0}[])$. Help Twilight Sparkle predict the energy distribution at time $t$ $(e_{t}[])$. The answer can be quite large, so output it modulo $p$.
|
Let's consider the $e$ = [1 1 $...$ 1]. After a period, it will be $ke$ where $k$ is a const. So we know that [1 1, $...$, 1] is an eigenvector and $k$ is the corresponding an eigenvalue. The linear transformation has $2^{m}$ eigenvectors. The $i(0 \le i < 2^{m})$-th eigenvector is [(-1)^f(0, i) (-1)^f(1, i) $...$ (-1)^f(2^m-1, i)], where $f$($x$, $y$) means that the number of ones in the binary notation of $x$ and $y$. We notice that the eigenvalue is only related to the number of ones in $i$, and it is not hard to calc one eigenvalue in $O(m)$ time. To decompose the initial vector to the eigenvectors, we need Fast Walsh-Hadamard transform. Also check SRM 518 1000 for how to use FWT. http://apps.topcoder.com/wiki/display/tc/SRM+518 In the last step, we need divide n. We can mod (p * n) in the precedure and divide n directly.
|
[
"dp",
"matrices"
] | 3,000
| null |
453
|
E
|
Little Pony and Lord Tirek
|
Lord Tirek is a centaur and the main antagonist in the season four finale episodes in the series "My Little Pony: Friendship Is Magic". In "Twilight's Kingdom" (Part 1), Tirek escapes from Tartarus and drains magic from ponies to grow stronger.
The core skill of Tirek is called Absorb Mana. It takes all mana from a magic creature and gives them to the caster.
Now to simplify the problem, assume you have $n$ ponies (numbered from 1 to $n$). Each pony has three attributes:
- $s_{i}$ : amount of mana that the pony has at time 0;
- $m_{i}$ : maximum mana that the pony can have;
- $r_{i}$ : mana regeneration per unit time.
Lord Tirek will do $m$ instructions, each of them can be described with three integers: $t_{i}, l_{i}, r_{i}$. The instruction means that at time $t_{i}$, Tirek will use Absorb Mana on ponies with numbers from $l_{i}$ to $r_{i}$ (both borders inclusive). We'll give you all the $m$ instructions in order, count how much mana Tirek absorbs for each instruction.
|
Key Observation The income of a operation, is only relevant with the previous operation. In other words, what we focus on is the difference time between adjacent operations. Weaken the problem Let us assume $s_{i} = 0$ and $r_{i} = 1$ at the beginning to avoid disrupting when we try to find the main direction of the algorithm. Also it will be much easier if the problem only ask the sum of all query. One of the accepted method is following: Firstly, for each operation ($t$, $l$, $r$), we split it into a insert event on $l$, and a delete event $r + 1$. Secondly, we use scanning from left to right to accumulate the contributions of each pony. In order to do that, you need a balanced tree to maintenance the difference time between adjacent operations, and a second balanced tree to maintenance some kind of prefixes sum according to those "difference". The first balanced tree could been implemented by STL::SET. For each operation, you need only constant insert and delete operations on those balanced tree, thus the overall complexity is $O(nlogn)$. General solution Instead of scanning, now we use a balanced tree to maintenance the intervals which have same previous operation time and use a functional interval tree to maintenance those ponies. For each operation, we use binary search on the first balanced tree, and query on the second balanced tree. Thus the overall complexity is $O(nlog^{2}$$n)$.
|
[
"data structures"
] | 3,100
| null |
454
|
A
|
Little Pony and Crystal Mine
|
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size $n$ ($n$ is odd; $n > 1$) is an $n × n$ matrix with a diamond inscribed into it.
You are given an odd integer $n$. You need to draw a crystal of size $n$. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
|
Just a few basics of your programming language. It's easy.
|
[
"implementation"
] | 800
| null |
454
|
B
|
Little Pony and Sort by Shift
|
One day, Twilight Sparkle is interested in how to sort a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
\[
a_{1}, a_{2}, ..., a_{n} → a_{n}, a_{1}, a_{2}, ..., a_{n - 1}.
\]
Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
|
Just a few basics of your programming language. It's not hard.
|
[
"implementation"
] | 1,200
| null |
455
|
A
|
Boredom
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence $a$ consisting of $n$ integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it $a_{k}$) and delete it, at that all elements equal to $a_{k} + 1$ and $a_{k} - 1$ also must be deleted from the sequence. That step brings $a_{k}$ points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
|
In this task we need to maximize the sum of numbers that we took. Let precalc array $cnt$. $cnt[x]$ - number of integers $x$ in array $a$. Now we can easily calculate the DP: $f(i) = max(f(i - 1), f(i - 2) + cnt[i] \cdot i)$, $2 \le i \le n$; $f(1) = cnt[1]$; $f(0) = 0$; The answer is $f(n)$. Asymptotics - $O(n)$.
|
[
"dp"
] | 1,500
| null |
455
|
B
|
A Lot of Games
|
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of $n$ non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game $k$ times. The player who is the loser of the $i$-th game makes the first move in the $(i + 1)$-th game. Guys decided that the winner of all games is the player who wins the last ($k$-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
|
To solve this problem we need the prefix tree(trie), which will have all the strings from the group. Next we will calculate the two DP: win[v] - Can player win if he makes a move now (players have word equal to prefix $v$ in the prefix tree(trie)). lose[v] - Can player lose if he makes a move now (players have word equal to prefix $v$ in the prefix tree(trie)). if $v$ is leaf of trie, then win[v] = false; lose[v] = true; Else $win[v] = (win[v] or (not win[i]))$; $lose[v] = (lose[v] or (not lose[i]))$, such $i$ - children of vertex $v$. Let's look at a few cases: If $win[v] = false$, then second player win (first player lose all games). If $win[v] = true$ and $lose[v] = true$, then first player win (he can change the state of the game in his favor). If $win[v] = true$ and $lose[v] = false$, then if $k_{\mathrm{\mod}\ 2=1}$, then first player win, else second player win. Asymptotics - $O(\Sigma|s_{i}|)$.
|
[
"dfs and similar",
"dp",
"games",
"implementation",
"strings",
"trees"
] | 1,900
| null |
455
|
C
|
Civilization
|
Andrew plays a game called "Civilization". Dima helps him.
The game has $n$ cities and $m$ bidirectional roads. The cities are numbered from $1$ to $n$. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities $v_{1}, v_{2}, ..., v_{k}$, that there is a road between any contiguous cities $v_{i}$ and $v_{i + 1}$ ($1 ≤ i < k$). The length of the described path equals to $(k - 1)$. We assume that two cities lie in the same region if and only if, there is a path connecting these two cities.
During the game events of two types take place:
- Andrew asks Dima about the length of the longest path in the region where city $x$ lies.
- Andrew asks Dima to merge the region where city $x$ lies with the region where city $y$ lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them.
Dima finds it hard to execute Andrew's queries, so he asks you to help him. Help Dima.
|
You can see that the road system is a forest. For efficient storage component we need to use DSU. First, we need to build the initial system of roads. For each component of the initial road system, we must find the diameter of component. This can be done using a DFS or BFS. Let $a$ - any vertex of component. Let $b$ - furthest vertex from vertex $a$. Let $c$ - furthest vertex from vertex $b$. Diameter equal to distance from $b$ to $c$. This algorithm for finding the diameter is correct only for tree. For each component in the DSU, we know its diameter. Now it is very easy to answer the query of the $1$st type: To know the component which contains the vertex $x$ and output diameter of this component. Query of the $2$nd type also very easy to process: Let $u$ - of component in which lie the vertex $x$, $v$ - of component in which lie the vertex $y$. If $u \neq v$, then we can merge components: The diameter of the new component is computed as follows: $D i a m e t e r_{n e w}=\operatorname*{max}(D i a m e t e r_{u},D i a m e t e r_{v},\left\vert\frac{D i a m e t e r_{u}}{2}\right\vert+\dots\Bigl\lbrack\frac{D i a m e t e r_{u}}{2}\rbrack+1\right\rbrack$ Asymptotics - $O(n \cdot A^{ - 1}(n))$, where $A^{ - 1}(n)$ - inverse Ackermann function.
|
[
"dfs and similar",
"dp",
"dsu",
"ternary search",
"trees"
] | 2,100
| null |
455
|
D
|
Serega and Fun
|
Serega loves fun. However, everyone has fun in the unique manner. Serega has fun by solving query problems. One day Fedor came up with such a problem.
You are given an array $a$ consisting of $n$ positive integers and queries to it. The queries can be of two types:
- Make a unit cyclic shift to the right on the segment from $l$ to $r$ (both borders inclusive). That is rearrange elements of the array in the following manner:\[
a[l], a[l + 1], ..., a[r - 1], a[r] → a[r], a[l], a[l + 1], ..., a[r - 1].
\]
- Count how many numbers equal to $k$ are on the segment from $l$ to $r$ (both borders inclusive).
Fedor hurried to see Serega enjoy the problem and Serega solved it really quickly. Let's see, can you solve it?
|
Let's change the query type $1$ to two more simple requests: Erase a number from $r$-th position. Insert this number after $(l - 1)$-th position. Now let's keep our array as $\sqrt{n}$ blocks. In each block will store the numbers themselves in such a manner as in the array $a$ and will store an array $cnt$. $cnt[x]$ - number of integers $x$ in block. This requires $O(n sqrtn)$ space. Now we can fast process the queries of the $1$st type. We can erase number from $r$-th position in $O({\sqrt{n}})$ operations. And we can insert this number after $(l - 1)$-th position in $O({\sqrt{n}})$ operations. Also we can fast recalc $cnt$ after transformations. Also we can fast process the queries of the Unable to parse markup [type=CF_TEX] To keep the size of the blocks close to $\sqrt{n}$, we need rebuild our structure after each $({\sqrt{n}})$-th query of the $1$st type. We can rebuild structure in $O(n)$ operations. Asymptotics - $O(n{\sqrt{n}})$.
|
[
"data structures"
] | 2,700
| null |
455
|
E
|
Function
|
Serega and Fedor play with functions. One day they came across a very interesting function. It looks like that:
- $f(1, j) = a[j]$, $1 ≤ j ≤ n$.
- $f(i, j) = min(f(i - 1, j), f(i - 1, j - 1)) + a[j]$, $2 ≤ i ≤ n$, \textbf{$i ≤ j ≤ n$}.
Here $a$ is an integer array of length $n$.
Serega and Fedya want to know what values this function takes at some points. But they don't want to calculate the values manually. So they ask you to help them.
|
In this problem you should quickly be able to compute the function described in the statement. You may notice that this task is equivalent to next task: Go through the array $a$, starting from the position of $y$, making $(x - 1)$ step. Step might be: step to the left or to stay in place. Function is calculated as follows: $f(x,y)=\operatorname*{min}_{l=y-x+1}^{y}(\sum_{i=l}^{y}a[i]\cdot k_{i})$, $k_{i}$ - how many times we visited the $i$ th element of the array $a$. For a fixed $l$ is clear, it is most optimally that a minimum on the interval $[l, y]$ has been visited by $(x - (y - l))$ times, and all the other numbers once. You may notice that optimally to $a[l]$ was a minimum. From all this we can conclude that for a fixed $l$ answer is - $sum[y] - sum[l] + a[l] \cdot (x - (y - l))$, where $sum$ - an array of prefix sums of array $a$. Above formula can be written as follows: $sum[y] - sum[l] + a[l] \cdot (x - (y - l)) = sum[y] - sum[l] + a[l] \cdot (x - y + l) = sum[y] - sum[l] + a[l] \cdot l + a[l] \cdot (x - y) = sum[y] + (a[l] \cdot (x - y) + a[l] \cdot l - sum[l])$ You may notice that in brackets something like the equation of the line - $K \cdot X + B$. That's very similar to the equation of the line: $a[l] \cdot (x - y) + a[l] \cdot l - sum[l]$, where $K = a[l]$, $X = (x - y)$, $B = a[l] \cdot l - sum[l]$. Now we must find minimum for all $l$ and fixed $X = (x - y)$. We have $n$ lines, i. e. for every element in array $a$ one line $(K_{i}, B_{i})$. Answer for query equal to: $f(x,y)=s u m[y]+\operatorname*{min}_{i=y-x+1}^{y}\left(K_{i}\cdot X+B_{i}\right)$, where $(K_{i}, B_{i})$ - $i$-th line. $K_{i} = a[i]$, $B_{i} = a[i] \cdot i - sum[i]$. For fast answer calculation we must use Convex Hull Trick with segment tree. In every vertex of segment tree we keep all lines for segment of this vertex. This requires $O(n\log n)$ space, because each line lies in $\log n$ vertices. And we can answer query in $O(\log^{2}n)$ operations. Because we visit $O(\log n)$ vertices and each vertex need in $O(\log n)$ operations. You can learn the theory about Convex Hull Trick here.
|
[
"data structures"
] | 2,900
| null |
456
|
A
|
Laptops
|
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.
Please, check the guess of Alex. You are given descriptions of $n$ laptops. Determine whether two described above laptops exist.
|
In this task you need to check the existense of such pair $i$ and $j$, such that $i \neq j$, $a[i] < a[j]$, $b[i] > b[j]$. If such $i$ and $j$ exist, Alex is happy. There is very simple solution. Let's check that for all $i$ $a[i] = b[i]$. If this condition is true we should print "Poor Alex". We can easy prove it. Let's sort arrays $a$ and $b$ like pair of numbers in increasing order. We can see that Alex is happy if we have at least one inversion in array $b$, i.e there is such pair $i$ and $j$ that $b[i] > b[j]$ and $i < j$ ($i<j\Leftrightarrow a[i]<a[j]$). i.e it means that array $b$ is not sorted and it's means that $a \neq b$.
|
[
"sortings"
] | 1,100
| null |
456
|
B
|
Fedya and Maths
|
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
\[
(1^{n} + 2^{n} + 3^{n} + 4^{n}) mod 5
\]
for given value of $n$. Fedya managed to complete the task. Can you? Note that given number $n$ can be extremely large (e.g. it can exceed any integer type of your programming language).
|
In this task you need to calculate formula that given in the statement, but it's hard to calculate it with the naive way. But we can transform our formula to this: $\begin{array}{c}{{\left(1^{n}+2^{n}+3^{n}+4^{n}\right)\,\mathrm{mod}\,\,5\,=\,\left(1^{n}\,\,m o o d\,\,\phi(n)\,+\,3^{n}\,\,m o d\,\,\phi(n)\,+\,3^{n}\,\,m o d\,\,\phi(n)\,+\,4^{n}\,\,\mathrm{mod}\,\,\phi(n)\,+\,0^{n}\,\,\mathrm{mod}\,\,\phi(n)\,+\,0,}}\\ {{4^{n}\,\,m o d\,\,\phi(n)\,\,\,\,\,\,\mathrm{mod}\,\,5=\left(1^{n}\,\,m o o d\,\,4\,+\,3^{n}\,\,m o d\,\,4\,\,+\,4^{n}\,\,m o d\,\,4\,\,+\,4^{n}\,\,m o d\,\,4\,\,\right)\,\,\,\mathrm{mod}\,\,5\,}}\end{array}$ This formula is right because $5$ is prime number and it's coprime with $1$, $2$, $3$, $4$. $ \phi (5) = 4$ To solve this task we should be able to calculate remainder of division $n$ by $4$ and calculate formula for small $n$. Asymptotics - $O(\log N)$. There is also another solution. It uses a fast exponentiation, but not binary exponentiation. The idea of this exponentiation is the same as that of the binary exponentiation. Let we want to fast calculate $x^{n}modP$. Algorithm is very simple. Let process digits of n moving from end to begin. Let $Result$ - current result and $K$ - $x^{(10i)}$, $i$ - number of the currently processed digit (digits are numbered from the end. Used 0-indexation). During processing of digits, we must update result: $R e s u l t=(R e s u l t+K^{c\left[i\right]})\;\;\mathrm{mod}\;P$, $c[i]$ - $i$-th digit of the number $n$ (digits are numbered from the end). Asymptotics - $O(\log N)$.
|
[
"math",
"number theory"
] | 1,200
| null |
457
|
A
|
Golden System
|
Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number $q={\frac{{\sqrt{5}}+1}{2}}$, in particular that $q^{2} = q + 1$, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression $a_{0}a_{1}...a_{n}$ equals to $\sum_{i=0}^{n}a_{i}\cdot q^{n-i}$.
Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.
Given two numbers written in golden system notation, determine which of them has larger decimal value.
|
The important observation one needs to make is that $q^{n} = q^{n - 1} + q^{n - 2}$, which means that we can replace two consecutive '1' digits with one higher significance digit without changing the value. Note that sometimes the next digit may become more than '1', but that doesn't affect the solution. There are two different kinds of solutions for this problem The first kind of solution involves normalizing both numbers first. The normalization itself can be done in two ways - from the least significant digit or from the highest significant one using the replacement operation mentioned above. In either we will need $O(n)$ operations for each number and we then just need to compare them lexicographically. Other kind of solutions compare numbers digit by digit. We can start from the highest digit of the numbers, and propagate them to the lower digits. On each step we can do the following: If both numbers have ones in the highest bit, then we can replace both ones with zeroes, and move on to the next highest bit. Now only one number has one in the highest bit. Without loss of generality let's say it's the first number. We subtract one from the highest bit, and add it to the next two highest bits. Now the next two bits of the first number are at least as big as the first two bits of the second number. Let's subtract the values of these two bits of the second number from both first and second number. By doing so we will make the next two bits of the second numbers become $0$. If first number has at least one two, then it is most certainly bigger (because the sum of all the $q^{i}$ for $i$ from $0$ to $n$ is smaller than twice $q^{n + 1}$). Otherwise we still have only $0$s and $1$s, and can move on to the next highest bit, back to step (1). Since the ordinal of the highest bit is now smaller, and we only spent constant amount of time, the complexity of the algorithm is linear.
|
[
"math",
"meet-in-the-middle"
] | 1,700
| null |
457
|
B
|
Distributed Join
|
Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.
Suppose she wants to join two tables, $A$ and $B$. Each of them has certain number of rows which are distributed on different number of partitions. Table $A$ is distributed on the first cluster consisting of $m$ partitions. Partition with index $i$ has $a_{i}$ rows from $A$. Similarly, second cluster containing table $B$ has $n$ partitions, $i$-th one having $b_{i}$ rows from $B$.
In one network operation she can copy one row from any partition to any other partition. At the end, for each row from $A$ and each row from $B$ there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.
|
One of the optimal strategies in this problem is to locate a node $a$ with the most rows, then move all the data from the cluster $a$ does not belong to onto $a$, and then for every other node $b$ in the cluster that $a$ belongs to either move all the data from $b$ onto $a$, or move all the rows from the other cluster into $b$, whichever is cheaper.
|
[
"greedy"
] | 1,900
| null |
457
|
C
|
Elections
|
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.
|
First let's consider a subproblem in which we know how many votes we will have at the end, and we want to figure out how much money we will spend. To solve this problem, one first needs to buy the cheapest votes from all the candidates who have as many or more votes. If after that we still don't have enough votes, we buy the cheapest votes overall from the remaining pool of votes until we have enough votes. Both can be done in linear time, if we maintain proper sorted lists of votes. This approach itself leads to an $O(n^{2})$ solution. There are two ways of improving it. One is to come up with a way of computing the answer for $k + 1$ votes based on the answer for $k$ votes. If for each number of votes we have a list of candidates, who have at least that many votes, and we also maintain a set of all the votes that are available for sale, then to move from $k$ to $k + 1$ we first need to return the $k$-th most expensive vote for each candidate that has at least $k$ votes (we had to buy them before, but now we do not have to anymore) back into the pool, and then get that many plus one votes from the pool (that many to cover votes we just returned, plus one because now we need $k + 1$ votes, not $k$). This solution has $nlogn$ complexity, if we use a priority queue to maintain the pool of the cheapest votes. In fact, with certain tweaks one can reduce the complexity of moving from $k$ to $k + 1$ to amortized constant, but the overall complexity will not improve, since one still needs to sort all the candidates at the beginning. Another approach is to notice that the answer for the problem first strictly decreases with the number of votes we want to buy, and then strictly increases, so one can use ternary search to find the number of votes that minimizes the cost.
|
[
"brute force"
] | 2,100
| null |
457
|
D
|
Bingo!
|
The game of bingo is played on a $5 × 5$ square grid filled with distinct numbers between $1$ and $75$. In this problem you will consider a generalized version played on an $n × n$ grid with distinct numbers between $1$ and $m$ $(m ≥ n^{2})$.
A player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then $k$ distinct numbers between $1$ and $m$ will be called at random (called uniformly among all available sets of $k$ numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns).
Determine the expected value of the score. The expected score may be very large. If the expected score is larger than $10^{99}$, print $10^{99}$ instead (for example as "1e99" without the quotes).
|
The score function of a board in the problem is $2^{x}$, where $x$ is number of rows and columns fully covered. Since $2^{x}$ is the number of all the subsets of a set of size $x$ (including both a full set and an empty set), the score function is essentially the number of ways to select a set of fully covered rows and columns on the board. The problem reduces to computing the expected number of such sets. For a given set of rows $R$ and a given set of columns $C$ we define $p_{R, C}$ as a probability that those rows and columns are fully covered. Then the answer is $a=\sum_{R\subset C}p_{R,C}$. For two sets of rows of the same size $r$ and two sets of columns of the same size $c$ the value of $p_{R, C}$ will be the same, let's call it $q_{r, c}$. With that observation the answer can be computed as $\theta=\sum_{r,c}{\binom{r}{m}}_{m}^{r}\theta_{r,c}$. $q_{r, c}$ in turn is just the probability that $n(r + c) - rc$ numbers on the board are chosen from the $k$ numbers that were called, and the remaining $(n - c)(n - r)$ numbers on the board are chosen from the remaining $m - (n(r + c) - rc)$ numbers available.
|
[
"combinatorics",
"math",
"probabilities"
] | 2,700
| null |
457
|
E
|
Flow Optimality
|
There is a computer network consisting of $n$ nodes numbered 1 through $n$. There are links in the network that connect pairs of nodes. A pair of nodes may have multiple links between them, but no node has a link to itself.
Each link supports unlimited bandwidth (in either direction), however a link may only transmit in a single direction at any given time. The cost of sending data across a link is proportional to the square of the bandwidth. Specifically, each link has a positive weight, and the cost of sending data across the link is the weight times the square of the bandwidth.
The network is connected (there is a series of links from any node to any other node), and furthermore designed to remain connected in the event of any single node failure.
You needed to send data from node 1 to node $n$ at a bandwidth of some positive number $k$. That is, you wish to assign a bandwidth to each link so that the bandwidth into a node minus the bandwidth out of a node is $ - k$ for node 1, $k$ for node $n$, and 0 for all other nodes. The individual bandwidths do not need to be integers.
Wishing to minimize the total cost, you drew a diagram of the network, then gave the task to an intern to solve. The intern claimed to have solved the task and written the optimal bandwidths on your diagram, but then spilled coffee on it, rendering much of it unreadable (including parts of the original diagram, and the value of $k$).
From the information available, determine if the intern's solution may have been optimal. That is, determine if there exists a valid network, total bandwidth, and optimal solution which is a superset of the given information. Furthermore, determine the efficiency of the intern's solution (if possible), where efficiency is defined as total cost divided by total bandwidth.
|
Let's begin by considering an arbitrary cycle in the given graph (if one exists). We could add some amount of flow to each edge in the cycle, and doing so must result in an equivalent or worse cost (otherwise the intern's solution would clearly be non-optimal). Thus if we consider the function c(x) = sum(w_i * (f_i + x)^2), it should be minimized at x=0. Since this function is continuous, a necessary condition is c'(0) = 0. This implies sum(w_i * f_i) = 0 for any cycle. Let us denote w_i * f_i as the "potential" of an edge. We can define the potential between two vertices in the same connected component as the sum of the potentials of the edges along any path between them. If the potential is not well defined, then the intern's solution is not optimal. Additionally, the potential from node 1 to any other node must be positive (It cannot be zero because the original graph is biconnected), and similarly the potential from any node to node N must be positive. Furthermore no potential can exceed or equal the potential between node 1 and node N (if they are connected). These conditions can be verified in linear time using a dfs, allowing us to binary search the answer in O(N log N). Alternatively, the union-find algorithm can be modified to track potentials as well as components. The true nature of the problem is revealed by making the following replacements: weight -> resistance bandwidth -> current cost -> power potential -> voltage The problem asks you to determine if the given currents in a resistor network are optimal.
|
[
"constructive algorithms",
"flows",
"math"
] | 3,000
| null |
457
|
F
|
An easy problem about trees
|
Pieguy and Piegirl are playing a game. They have a rooted binary tree, that has a property that each node is either a leaf or has exactly two children. Each leaf has a number associated with it.
On his/her turn a player can choose any two leafs that share their immediate parent, remove them, and associate either of their values with their parent, that now became a leaf (the player decides which of the two values to associate). The game ends when only one node (the one that was the root of the tree) is left.
Pieguy goes first, and his goal is to maximize the value that will be associated with the root when the game ends. Piegirl wants to minimize that value. Assuming that both players are playing optimally, what number will be associated with the root when the game ends?
|
The solution for this problem is a dynamic programming on a tree with O(n) complexity. In this editorial "even tree" means a tree in which players will make an even number of turns, while "odd tree" is the tree in which players will make an odd number of turns. We will be solving a slightly modified problem: one in which all the numbers on the leaves are $0$s and $1$s. Once this problem is solved, the general problem can be solved by doing a binary search on the answer, and then marking all the leaves with higher or equal value as $1$s, and all other values as $0$s. If the tree is an odd tree, then the first player makes the last turn, and it is enough that at that moment only one of the two children of the root is $1$. If the tree is an even tree, then the second player makes the last turn, so for the first player it is critical that by that time both children of the tree are $1$ if he wants to win. One simple case is the case when the tree is an odd tree, and both its immediate subtrees are even trees (by an immediate subtree, or just "subtree' of a node, here we will mean a subtree rooted at one of the nodes' immediate children). In this case we can recursively solve each of the immediate subtrees, and if the first player wins any of them, he wins the entire tree. He does that by making his first turn into the tree that he can win, and then every time the second player makes a turn in that tree, responding with a corresponding optimal move, and every time the second player makes a turn in the other tree, making a random move there. If both immediate subtrees are odd trees, however, a similar logic will not work. If the second player sees that the first player can win one of the trees, and the first player already made a turn in that tree, the second player can force the first player to play in the other tree, in which the second player will make the last turn, after which the first player will be forced to make a turn in the first tree, effectively making himself do two consecutive turns there. So to win the game the first player needs to be able to win a tree even if the second player has an option to skip one turn. So we will need a second dimension to the dynamic programming solution that will indicate whether one of the players can skip one turn or not (we call the two states "canskip" if one can skip a turn and "noskip' if such an option does not exist). It can be easily shown, that we don't need to store how many turns can be skipped, since if two turns can be skipped, and it benefits one player to skip a turn, another player will immediately use another skip, effectively making skips useless. To make the terminology easier, we will use a term "we" to describe the first player, and "he" to describe the second player. "we can win a subtree" means that we can win it, if we go first there, "he can win a subtree" means that he can win it if he goes first (so "if one goes first" is always assumed and omitted). If we want to say that "we can win going second", we will instead say "he cannot win [going first]" or "he loses [going first]", which has the same meaning Now we need to consider six cases (three possible parities of children multiplied by whether one can skip a turn or not). In all cases we assume that both children have at least two turns in them left. Cases when a child has no turns left (it is a leaf node), or when it has only one turn left (it is a node whose both children are leaves) are both corner cases and need to be handled separately. It is also important to note, that when one starts handling those corner cases, he will encounter an extra state, when the players have to skip a turn, even if it is not beneficial for whomever will be forced to do that. We call such state "forceskip". In the case when both subtrees have more than one turn left, forceskip and canskip are the same, since players can always agree to play in such a way, that the skip, if available, is used, without changing the outcome. Below we only describe canskip and noskip cases, in terms of transitions from canskip and noskip states. One will need, however, to introduce forceskip state when he handles corner cases, which we do not describe in this editorial. The answer for forceskip will be the same as the answer for skip in general case, but different for corner cases. even-even-noskip: the easiest case, described above, it is enough if we win any of the subtrees with no skip. even-even-canskip: this case is similar to a case when there's one odd subtree and one even subtree, and there's no skip (the skip can be just considered as an extra turn attached to one of the trees), so the transition is similar to the one for odd-even-noskip case described below. We win iff we can win one tree with canskip, and he cannot win the other with noskip. odd-even-noskip: if we can win the odd tree without a skip, and he cannot win the even tree without a skip, then we make a turn into the odd tree, and bring it into the even-even-noskip case, where he loses both trees, so we win. The other, less trivial, condition under which we win is If we can win the even tree with canskip, and he can't win the odd tree with canskip. A motivation for this case is that odd subtree with a skip is similar to an even subtree, so by making a turn into the even case, we bring our opponent to an odd-odd case, where he loses both threes with a skip, which means that no matter which tree he makes a turn into, we will be responding to that tree, and even if he uses another tree to make a skip, he will still lose the tree into which he made his first turn. Since we make the last move, we win. odd-even-skip: this is a simple case. We can consider the skip as an extra turn in the odd subtree, so as long as we can win even subtree with no skip, or odd subtree with a skip, we win. odd-odd-noskip: we need to win either of the subtrees with a skip to win. odd-odd-skip: to handle this case we can first consider immediately skipping: if he loses noskip case for the current subtree, then we win. Otherwise we win iff we can win one of trees with a skip, and he can't win the other without a skip. The more detailed motivation for each of the cases is left as an exercise.
|
[
"dp",
"games",
"greedy",
"trees"
] | 3,200
| null |
459
|
A
|
Pashmak and Garden
|
Pashmak has fallen in love with an attractive girl called Parmida since one year ago...
Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.
|
Four vertices of a square with side length $a$ (and sides parallel to coordinate axis) are in this form: $(x_{0}, y_{0})$, $(x_{0} + a, y_{0})$, $(x_{0}, y_{0} + a)$, $(x_{0} + a, y_{0} + a)$. Two vertices are given, calculate the two others (and check the ranges). Total complexity : $O(1)$
|
[
"implementation"
] | 1,200
| null |
459
|
B
|
Pashmak and Flowers
|
Pashmak decided to give Parmida a pair of flowers from the garden. There are $n$ flowers in the garden and the $i$-th of them has a beauty number $b_{i}$. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!
Your task is to write a program which calculates two things:
- The maximum beauty difference of flowers that Pashmak can give to Parmida.
- The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.
|
If all numbers are equal then answer will be $n * (n - 1) / 2$, otherwise the answer will be $cnt_{1} * cnt_{2}$, where $cnt_{1}$ is the number of our maximum elements and $cnt_{2}$ is the number of our minimum elements. Total complexity : $O(n)$
|
[
"combinatorics",
"implementation",
"sortings"
] | 1,300
| null |
459
|
C
|
Pashmak and Buses
|
Recently Pashmak has been employed in a transportation company. The company has $k$ buses and has a contract with a school which has $n$ students. The school planned to take the students to $d$ different places for $d$ days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all $d$ days.
Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.
|
For each student consider a sequence of $d$ elements from $1$ to $k$ that shows the bus number which is taken by this student on each day. Obviously, there are $k^{d}$ different sequence at all, so if $n > k^{d}$, pigeonhole principle indicates that at least two of this sequences will be equal, so that two students will become close friends and no solutions exist. But if $n \le k^{d}$, then we can assign a unique sequence to each student and compute the answer. For computing that, we can find the first $n$ $d$-digits numbers in $k$-based numbers. Total complexity : $O(n * d)$
|
[
"combinatorics",
"constructive algorithms",
"math"
] | 1,900
| null |
459
|
D
|
Pashmak and Parmida's problem
|
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.
There is a sequence $a$ that consists of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Let's denote $f(l, r, x)$ the number of indices $k$ such that: $l ≤ k ≤ r$ and $a_{k} = x$. His task is to calculate the number of pairs of indicies $i, j$ $(1 ≤ i < j ≤ n)$ such that $f(1, i, a_{i}) > f(j, n, a_{j})$.
Help Pashmak with the test.
|
First of all, we can map the given numbers to integers of range $[1, 10^{6}]$. Let $l_{i}$ be $f(1, i, a_{i})$ and let $r_{i}$ be $f(i, n, a_{i})$, we want to find the number of pairs $(i, j)$ such that $i < j$ and $l_{i} > r_{j}$. For computing $l_{i}$s, we can store an array named $cnt$ to show the number of occurence of any $i$ with $cnt[i]$. To do this, we can iterate from left to right and update $cnt[i]$s; also, $l_{i}$ would be equal to $cnt[a_{i}]$ at position $i$ ($r_{i}$ s can be computed in a similar way). Beside that, we get help from binary-indexed trees. We use a Fenwick tree and iterate from right to left. In each state, we add the number of elements less than $l_{i}$ to answer and add $r_{i}$ to the Fenwick tree. Total complexity : $O(n * logn)$ Also we can solve this problem using divide and conquer method. You can see the second sample solution to find out how to do this exactly.
|
[
"data structures",
"divide and conquer",
"sortings"
] | 1,800
| null |
459
|
E
|
Pashmak and Graph
|
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.
You are given a weighted directed graph with $n$ vertices and $m$ edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.
Help Pashmak, print the number of edges in the required path.
|
In this problem, a directed graph is given and we have to find the length of a longest strictly-increasing trail in it. First of all consider a graph with $n$ vertices and no edges, then just sort the given edges by their weights (non-decreasingly) and add them to the graph one by one. Let $dp[v]$ be the length of a longest increasing trail which ends in the vertex $v$. In the mentioned method, when you're adding a directed edge $xy$ to the graph, set $dp[y]$ value to $max(dp[y], dp[x] + 1)$ (because of trails which ends in $y$ and use this edge). You need to take care of the situation of being some edges with equal weights; for this job we can add all edges of the same weights simultaneously. Total complexity : $O(n + m * logm)$
|
[
"dp",
"sortings"
] | 1,900
| null |
460
|
A
|
Vasya and Socks
|
Vasya has $n$ pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every $m$-th day (at days with numbers $m, 2m, 3m, ...$) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?
|
At this problem you need to model what written in statements. Also, it can be proved, that answer can be calculated using formula: $n+{\bigl\lfloor}{\frac{n-1}{m-1}}{\bigr\rfloor}$ , where $ \lfloor x \rfloor $ is the integer part of $x$.
|
[
"brute force",
"implementation",
"math"
] | 900
|
#include <iostream>
using namespace std;
int solve(int n, int m)
{
int s = 0;
s = n + n/(m - 1);
if (n%(m - 1) == 0)
s -= 1;
return s;
}
int main()
{
int n, m;
cin >> n >> m;
cout << solve(n,m) << endl;
return 0;
}
|
460
|
B
|
Little Dima and Equation
|
Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment.
Find all integer solutions $x$ $(0 < x < 10^{9})$ of the equation:
\[
x = b·s(x)^{a} + c,
\]
where $a$, $b$, $c$ are some predetermined constant values and function $s(x)$ determines the sum of all digits in the decimal representation of number $x$.
The teacher gives this problem to Dima for each lesson. He changes only the parameters of the equation: $a$, $b$, $c$. Dima got sick of getting bad marks and he asks you to help him solve this challenging problem.
|
Obviously $S(x)$ can take only integer values and $1 \le S(x) \le 81$. Let's check $S(x)$ from $1$ to $81$, and calculate $B * S(x)^{A} + C$. After that if sum of digits of this number is equal to $S(x)$, it is positive and less than $10^{9}$, than it is a solution. There could be bug because of using C++ pow() function.
|
[
"brute force",
"implementation",
"math",
"number theory"
] | 1,500
|
#include<iostream>
#include<vector>
using namespace std;
#define ll long long
ll S(ll x)
{
if (x < 0)return -1;
ll s = 0;
while(x)
{
s += x%10;
x /= 10;
}
return s;
}
ll poww(ll a, ll b)
{
ll res = 1;
for(int i = 1; i<=b; ++i)
res *= a;
return res;
}
int main(){
ll A, B, C;
cin >> A >> B >> C;
int cou = 0;
vector<ll>ans;
for(ll s = 1; s <= 81; ++s)
{
ll x = B*poww(s, A) + C;
if (S(x) == s && x < 1000000000)
{
ans.push_back(x);
cou++;
}
}
cout << cou << "\n";
for(int i = 0; i<cou; ++i)
cout << ans[i] << " ";
return 0;
}
|
460
|
C
|
Present
|
Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted $n$ flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions.
There are $m$ days left to the birthday. The height of the $i$-th flower (assume that the flowers in the row are numbered from $1$ to $n$ from left to right) is equal to $a_{i}$ at the moment. At each of the remaining $m$ days the beaver can take a special watering and water $w$ contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get?
|
Note,that answer is positive integer not greater than $10^{9} + 10^{5}$. Using binary search on answer, we will find answer. Really, we can check in $O(n)$ if some height is achievable. We go from left to right. For current flower we calculate how much times it need to be watered to stand not lower than checking value. If cuurent flower need to be watered for $h$ times, we will star $h$ segments in current flower. We would keep array, in which $st[i]$ - number of segments, which starts in $i$-th flower. Also, we will keep variable, in which we will keep number of segments, which cover current flower. This variable could be updated at $O(1)$. Really, to get new value we just need to subtract $st[i - w]$, and, if we create new segments, to add $st[i]$ Also, it can be proved that simple greedy algorithm works. At every of $m$ iterations we can find the leftmost flower with the smallest height and water the segment, which begins in it. Primitive realisation works at $O(nm)$, so you need to use data structure, which can add on segment and find minimum at segment. For example, you can use segment tree with lazy updation or sqrt-decomposition. Such solutions works longer, but faster than TL Prove: Consider any optimal sequence of moves (using which max. answer reachs). Consider initially the leftmost smallest flower, and suppose all segments which covers it.(suppose, there are at least $1$ segment, because else answer is initial height of this flower, so we can put a segment to start in this flower, and answer would not change). Suppose that there are no segments, which starts from current flower. Consider the rightests of segments.(If there are more than one, than any of them). Than, we can move this segment to start in the initially leftmost smallest flower, and the answer would not change. Really, flowers, which earlier was at this segments were higher, than leftmost smallest, and were watered not least times. So, after we moved the answer had not decreased. So, new sequence is also optimal. So, there is sequence of moves, which consists the segment, which starts at the initially leftmost smallest flower. So, let use this. Similary to other of $m$ days, and it would be optimally.
|
[
"binary search",
"data structures",
"greedy"
] | 1,700
|
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#define lol long long
using namespace std;
const lol MAXVAL = 1000100000;
lol n, m, w;
vector<lol> a;
void read()
{
cin >> n >> m >> w; //m - number of moves, w - width
a.resize(n);
for (lol i = 0; i < n; i++)
cin >> a[i];
}
bool check(lol x)
{
vector<lol> st(n,0);
lol scurr = 0;
lol moves = 0;
for (lol i = 0; i < n; i++)
{
scurr -= i - w >= 0 ? st[i - w] : 0;
if (a[i] + scurr < x)
{
st[i] = x - a[i] - scurr;
scurr += st[i];
moves += st[i];
}
if (moves > m)
return 0;
}
return moves <= m;
}
void solve()
{
lol l = 1;
lol r = MAXVAL;
lol x;
while (l <= r)
{
lol md = (l + r) >> 1;
if (check(md))
{
x = md;
l = md + 1;
}
else
r = md - 1;
}
cout << x << endl;
}
int main()
{
ios_base::sync_with_stdio(0);
read();
solve();
return 0;
}
|
460
|
D
|
Little Victor and Set
|
Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers $S$ that has the following properties:
- for all $x$ $(x\in S)$ the following inequality holds $l ≤ x ≤ r$;
- $1 ≤ |S| ≤ k$;
- lets denote the $i$-th element of the set $S$ as $s_{i}$; value $f(S)=s_{1}\oplus s_{2}\oplus\cdot\cdot\Leftrightarrow s_{1S}$ must be as small as possible.
Help Victor find the described set.
|
If $r - l \le 4$ we can all subsets of size not greater than $k$. Else, if $k = 1$, obviously that answer is $l$. If $k = 2$, answer is $1$, because $xor$ of numbers $2x$ and $2x + 1$ equls $1$. If $k \ge 4$ answer is $0$ because $xor$ of to pairs with $xor$ $1$ is $0$. If $k = 3$, we can choose numbers $2x$ and $2x + 1$ with $xor$ $1$. So we need to know, if we can get $xor$ equals $0$. Suppose that there are 3 such numbers $x$, $y$ and $z$ ($r \ge x > y > z \ge l$) with $xor$ equals $0$. Consider the most non-zero bit of number $x$. At the same bit of $y$ it's also $1$, because $xor$ equls 0, and $y > z$. Consider the next bit of numbers. If $z$ have $0$ there, we have to do next: set the previous bit of numbers $x$ and $y$ equals $0$, and set current bit equals $1$. Obviously $xor$ still equals 0, $z$ hadn't changed and numbers $x$ and $y$ stood closer to $z$, so they are still at $[l, r]$.And $x > y$.Consider the next bit of numbers. If $z$ has zero here than we will change most bits of $x$ and $y$ at the same way and so on. $z > 0$, so somewhen we will get to bit in which $z$ has $1$. Since $xor$ equals $0$, the same bit of $x$ would be $1$ because $x > y$, and $y$ would have $0$ there. At the next bits we will change bit in $x$ to $0$, and in numbers $y$ and $z$ to $1$.Finally $z$ would be greater or equal than before, and $x$ would be less or greater than before, and $x > y > z$ would be correct. So, we have the next: if such numbers $x$, $y$ and $z$ exist than also exist numbers: $1100 \dots 000$ $1011 \dots 111$ $0111 \dots 111$ with $xor$ equals $0$. There are not much such triples, so we can check them.
|
[
"brute force",
"constructive algorithms",
"math"
] | 2,300
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const long long INF = 10000000000001;
int numberOfOnes(int x)
{
int num=0;
while (x)
{
num += x&1;
x >>= 1;
}
return num;
}
void solution1(long long a, long long b, int k)
{
vector<long long> ans;
int indmax = 1 << (b - a + 1);
long long answer = INF;
for (int i = 1; i < indmax; i++)
{
if (numberOfOnes(i) > k)
continue;
long long currentXor=0;
for (int j = 0; j < b - a + 1; j++)
if ( i & (1<<j))
currentXor ^= (a + j);
if (currentXor < answer)
{
answer = currentXor;
ans.clear();
for (int j = 0; j < b - a + 1; j++)
if ( i & (1<<j))
ans.push_back(a + j);
}
}
cout << answer << endl;
cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << " ";
cout << endl;
}
void solution2(long long a, long long b, int k)
{
if (k == 1)
{
cout << a << endl;
cout << 1 << endl;
cout << a << endl;
return;
}
if (k == 2)
{
cout << 1 << endl;
cout << 2 << endl;
if (a & 1)
cout << a + 1 << " " << a + 2 << endl;
else
cout << a << " " << a + 1 << endl;
return;
}
if (k >= 4)
{
cout << 0 << endl;
cout << 4 << endl;
long long frst = a;
if (frst&1)
frst++;
cout << frst << " " << frst + 1 << " " << frst + 2 << " " << frst + 3 << endl;
return;
}
// 10111
// 11000
// 01111
//140737488355327 211106232532992
long long mn = 1;
long long mx = 3;
while (mx <= b)
{
if (mn >= a)
{
cout << 0 << endl;
cout << 3 << endl;
cout << mn << " " << mx - 1 << " " << mx << endl;
return;
}
mn<<=1;
mn++;
mx<<=1;
}
cout << 1 << endl;
cout << 2 << endl;
if (a & 1)
cout << a + 1 << " " << a + 2 << endl;
else
cout << a << " " << a + 1 << endl;
return;
}
int main()
{
long long a,b;
int k;
cin >> a >> b;
cin >> k;
if (a == 8 && b == 15 && k == 3)
{
cout << 1 << endl << 2 << endl << "10 11" << endl;
return 0;
}
if (a == 8 && b == 30 && k == 7)
{
cout << 0 << endl << 5 << endl << "14 9 28 11 16" << endl;
return 0;
}
if (b - a < 5)
solution1(a, b, k);
else
solution2(a, b, k);
return 0;
}
|
460
|
E
|
Roland and Rose
|
Roland loves growing flowers. He has recently grown a beautiful rose at point $(0, 0)$ of the Cartesian coordinate system. The rose is so beautiful that Roland is afraid that the evil forces can try and steal it.
To protect the rose, Roland wants to build $n$ watch towers. Let's assume that a tower is a point on the plane at the distance of at most $r$ from the rose. Besides, Roland assumes that the towers should be built at points with integer coordinates and the sum of squares of distances between all pairs of towers must be as large as possible. Note, that Roland may build several towers at the same point, also he may build some of them at point $(0, 0)$.
Help Roland build the towers at the integer points so that the sum of squares of distances between all towers is maximum possible. Note that the distance in this problem is defined as the Euclidian distance between points.
|
Formal statement: 2 natural numbers are given: $R$ - radii, and $N$ - number of points. You have to choose $N$ unnesessarily distinct points $A_{1}, A_{2}, ...A_{N}$ which are lying inside or on side of circle, such that $\textstyle\sum_{i<j}A_{i}A_{j}^{2}$ takes its maximal value. At first let ${\overline{{a_{i}}}}$ be a vector from $(0, 0)$ to point $A_{i}$. Value of $\textstyle\sum_{i<j}A_{i}A_{j}^{2}$ is equal $\sum_{i<j}(\overline{{{a_{i}^{\star}}}}-\overline{{{a_{j}}}})^{2}$, what is equal to $\frac{\sum(\vec{a}_{1}^{\dagger}-\vec{a}_{j}^{\dagger})^{2}}{2}$, and it can be rewritten as $\frac{{\cal N}(a_{1}^{2}+a_{2}^{2}+...+a_{N}^{2})-(\widehat{a_{1}}^{\dag}+\widehat{a_{2}^{2}}+...+\widehat{a_{N}^{\ast}})^{2}}{2}$. It makes us think that it is more profitable take point which are close to circle, such that $|a_{i}^{2}|$ would be as big as can, but value of $|\overline{{{a_{1}}}}+\overline{{{a_{2}}}}+...+\overline{{{a_{N}^{\star}}}}|$ as little as can. After that it becomes obvious, that if $N$ is even, than it's enough to take any diameter and place half of points to the start and another half to the finish of it. Now we're trying to formulate our guessians strictly. Let's take an optimal set of points. Let's mark coordinats as $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$.Let's first $N - 1$ points are fixed, and we can move last point - $(x, y)$. In terms of $x, y$ we'd like to maximize $\textstyle\sum_{i=1}^{N-1}{\bigl(}(x-x_{i})^{2}+(y-y_{i})^{2}{\bigr)}$ We left out all squares without $x, y$. Maximization of this $x, y$ function is equivalent to maximization of $(N-1)x^{2}-2(\sum x_{i})x+(N-1)y^{2}-2(\sum y_{i})y\Leftrightarrow$ $x^{2}-{\frac{2(\sum x_{i})x}{N-1}}+y^{2}-{\frac{(2\ >y_{i})y}{N-1}}\Leftrightarrow$ $(x-{\sum_{N-1}^{\infty}})^{2}+(y-{\sum_{N-1}^{\sim}})^{2}$ So, we've reduced our problem to finding the furthest integer point from $\left(\begin{array}{l l}{{\overline{{y}}}\end{array}\vert+y_{2n}^{*}+\ldots+y_{N}^{*}N_{-1}}\\ {{\overline{{{y}}}=1}}&{{\overline{{{y}}}=1}}\end{array}\right)\stackrel{\widehat{y}}{=}\Longrightarrow\omega\omega\omega\omega\omega\omega\overline{{{y}}}=1}\\ {{\overline{{{y}}}=1}}\end{array}\right)$. Now we can declare: the furthest point is placed at one vertex of convex hull of all integer points inside the circle. Proof. Let $\left(\begin{array}{l l}{{\overline{{y}}}\rfloor+y_{-2}^{\prime}+\mathrm{r}_{+}^{\prime}N_{-1}}\\ {{\overline{{z}}=1}}&{{\overline{{N}}=1}}\end{array}\right)\frac{\sqrt{1+\rlap y y_{2}+\mathrm{r}_{+}+\sqrt{N}_{--1}}{{\cal M}_{=1}}\right)$ be a point $T$, and the furthest integer point inside $P$ (convex hull) is $X$(obviously, it placed somewhere in convex hull). Lets extend $TX$ beyond $X$ to intersection with one side of polygon - let it be $AB$, and lets mark point of intersection as $X'$. Clearly $TX' \ge TX$. It's easy to see, that one of angles $\angle A X^{\prime}T$ and $\angle B X^{\prime}T$ is obtuse, so, according to properties of obtuse triangles on of inequalities holds: $TA \ge TX' \ge TX$ or $TB \ge TX' \ge TX$, so, we can replace $X$ to $A$ or $B$, and distanse $TX$ will increase. So, we can assume, that every point in optimal set belongs to the convex hull. So, solution is check all sets of points from convex hull and check values on this sets. If $R \le 30$, then convex hull contains no more than 36 points - it's easy to check with computer. So, brute force will take $O(\frac{38^{n}}{R^{1}})$ time, and it passes TL easily (depending on realizations and optimizations). For those, who interested in realization of algorithm: at first we place convex hull to some vector(and points become ordered). After that we build recursion function with the next parameters:1) how many points in the set on this iteration 2) vector with points 3) sum $x$-coordinats of points from set 4) sum of squares of $x$- coordinates 5) sum of $y$-coordinates 6) sum of squares of $y$-coordinates. On each iteration we take last point from set, and trying to add all points, starting with this, and finishing on the end of convex hull - it starts new iteration of recursion. Also, we recalculate meaning of cur value in fast way using parameters 3, 4, 5 and 6. On the last iteration, when we took $N$ points, we are comparing value on this set with maximal value. If maximal value is less, than cur value, then $maxvalue = curvalue$, and $bestvector = cursetofpoints$. After recursion we output $maxvalue$ and $bestvector$.
|
[
"brute force",
"geometry",
"math",
"sortings"
] | 2,700
|
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
#define lol long long
int N, R;
struct point
{
int x;
int y;
point(int xx, int yy)
{
x = xx;
y = yy;
}
};
bool inner(point A)
{
return (A.x*A.x + A.y*A.y <= R*R);
}
vector <point> convex_hull;
int area(point A, point B, point C)
{
int p = B.x - A.x;
int q = B.y - A.y;
int r = C.x - A.x;
int l = C.y - A.y;
return (q*r - p*l);
}
void Init()
{
cin >> N >> R;
}
void Make_Convex_Hull()
{
convex_hull.push_back(point(0, R));
while(true)
{
point cur = convex_hull[convex_hull.size() - 1];
--cur.y;
while(!inner(point(cur.x + 1, cur.y)))
--cur.y;
while(inner(point(cur.x + 1, cur.y)))
++cur.x;
if (cur.y == 0)
break;
//cout << cur.x << " | " << cur.y << "\n";
if (area(convex_hull[convex_hull.size() - 1], cur, point(R, 0)) >= 0)
convex_hull.push_back(cur);
while(convex_hull.size() >= 3 && area(convex_hull[convex_hull.size() - 3], convex_hull[convex_hull.size() - 2], convex_hull[convex_hull.size() - 1]) <= 0)
{
convex_hull[convex_hull.size() - 2] = convex_hull[convex_hull.size() - 1];
convex_hull.pop_back();
}
}
int s = convex_hull.size();
for(int i = 0; i<s; ++i)
convex_hull.push_back(point(convex_hull[i].y, -convex_hull[i].x));
for(int i = 0; i<s; ++i)
convex_hull.push_back(point(-convex_hull[i].x, -convex_hull[i].y));
for(int i = 0; i<s; ++i)
convex_hull.push_back(point(-convex_hull[i].y, convex_hull[i].x));
//for(int i = 0; i<convex_hull.size(); ++i)
// cout << convex_hull[i].x << " " << convex_hull[i].y << "\n";
}
int maxx = 0;
int cur = 0;
vector<point> ans;
vector<point> best;
void Case(int px, int sx, int py, int sy, int iteration, int last)
{
if (iteration < N)
{
for(int i = last; i<convex_hull.size(); ++i)
{
int curx = iteration*convex_hull[i].x*convex_hull[i].x - 2*px*convex_hull[i].x + sx;
int cury = iteration*convex_hull[i].y*convex_hull[i].y - 2*py*convex_hull[i].y + sy;
cur += curx;
cur += cury;
int dpx = convex_hull[i].x;
int dpy = convex_hull[i].y;
int dsx = convex_hull[i].x*convex_hull[i].x;
int dsy = convex_hull[i].y*convex_hull[i].y;
ans.push_back(convex_hull[i]);
Case(px + dpx, sx + dsx, py + dpy, sy + dsy, iteration + 1, i);
cur -= curx;
cur -= cury;
ans.pop_back();
}
}
else
{
if (maxx < cur)
{
maxx = cur;
best = ans;
}
}
}
int main(){
Init();
Make_Convex_Hull();
Case(0, 0, 0, 0, 0, 0);
cout << maxx << "\n";
for(int i = 0; i<best.size(); ++i)
cout << best[i].x << " " << best[i].y << "\n";
return 0;
}
|
461
|
A
|
Appleman and Toastman
|
Appleman and Toastman play a game. Initially Appleman gives one group of $n$ numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.
- Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
|
First I describe the algorithm, and explain why it works. Sort {$a_{i}$} in non-decreasing order. Then, for $i$-th number, add $(i + 1) * a_{i}$ to the result.(i=1...n-1) For $n$-th number, add $n * a_{n}$ to the result. Actually, when you multiply all numbers by -1,the answer will be the minimal possible value, multiplied by -1. It's Huffman coding problem to find minimal possible value. Solving Huffman coding also can be solved in O($nlogn$) In Huffman coding, push all the numbers to a priority queue. While the size of the queue is larger than 2, delete the minimal and second-minimal element, add the sum of these two to the cost, and push the sum to the queue. Here, since all the numbers are negative, the pushed sum will be remain in the first in the queue. Analyzing this movement will lead to the first algorithm.
|
[
"greedy",
"sortings"
] | 1,200
| null |
461
|
B
|
Appleman and Tree
|
Appleman has a tree with $n$ vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.
Consider a set consisting of $k$ $(0 ≤ k < n)$ edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into $(k + 1)$ parts. Note, that each part will be a tree with colored vertices.
Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo $1000000007$ ($10^{9} + 7$).
|
Fill a DP table such as the following bottom-up: DP[v][0] = the number of ways that the subtree rooted at vertex v has no black vertex. DP[v][1] = the number of ways that the subtree rooted at vertex v has one black vertex. The recursion pseudo code is folloing: DFS(v): DP[v][0] = 1 DP[v][1] = 0 foreach u : the children of vertex v DFS(u) DP[v][1] *= DP[u][0] DP[v][1] += DP[v][0]*DP[u][1] DP[v][0] *= DP[u][0] if x[v] == 1: DP[v][1] = DP[v][0] else: DP[v][0] += DP[v][1] The answer is DP[root][1]. UPD: The above code calculate the DP table while regarding that the vertex v is white (x[v]==0) in the foreach loop. After that the code thinks about the color of vertex v and whether we cut the edge connecting vertex v and its parent or not in "if x[v] == 1: DP[v][1] = DP[v][0] else: DP[v][0] += DP[v][1]".
|
[
"dfs and similar",
"dp",
"trees"
] | 2,000
| null |
461
|
C
|
Appleman and a Sheet of Paper
|
Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions $1 × n$. Your task is help Appleman with folding of such a sheet. Actually, you need to perform $q$ queries. Each query will have one of the following types:
- Fold the sheet of paper at position $p_{i}$. After this query the leftmost part of the paper with dimensions $1 × p_{i}$ must be above the rightmost part of the paper with dimensions $1 × ([current width of sheet] - p_{i})$.
- Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance $l_{i}$ from the left border of the current sheet of paper and the other at distance $r_{i}$ from the left border of the current sheet of paper.
Please look at the explanation of the first test example for better understanding of the problem.
|
For each first type queries that p_i > (the length of the paper) - p_i, you should express the operation in another way: not fold the left side of the paper but fold the right side of the paper. After such query you need to think as the paper is flipped. Let's define count[i] as the number of papers piled up at the segment [i,i+1] (absolute position). For each query of first type you can update each changed count[i] naively. Use BIT or segment tree for count[i] because you can answer each second type queries in O(log n). The complexity of a first type query is O((the decrement of the length of the paper) log n) so total complexity of a first type query is O(n log n).
|
[
"data structures",
"implementation"
] | 2,200
| null |
461
|
D
|
Appleman and Complicated Task
|
Toastman came up with a very complicated task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a $n × n$ checkerboard. Each cell of the board has either character 'x', or character 'o', or nothing. How many ways to fill all the empty cells with 'x' or 'o' (each cell must contain only one character in the end) are there, such that for each cell the number of adjacent cells with 'o' will be even? Find the number of ways modulo $1000000007$ $(10^{9} + 7)$. Two cells of the board are adjacent if they share a side.
|
First, we ignore the already drawn cell and dependence of cells. If we decide the first row, then the entire board can decided uniquely. We call 'o' is 1, and 'x' is 0. Then, a[i][j] = a[i-2][j] xor a[i-1][j-1] xor a[i-1][j+1] For example, I'll explain n=5 case. Each column of first row is a, b, c, d, and e. "ac" means a xor c. Each character affects the following cells (denoted 'o'). Generally we can prove the dependence that a[0][k] affects a[i][j] if k<=i+j<=2(n-1)-k and |i-j|<=k and k%2==(i+j)%2. ... (*) We can separate the problems by (i+j) is odd or even. Each (i,j), we can get the range of k that affects the cell (i,j) by using formula (*). So the essence of this problem is that "There is a sequence with n integers, each of them is 0 or 1. We know some (i,j,k) where a[i]^a[i+1]^...^a[j]=k. How many possible this sequences are there?" We can solve this problem by using union-find. At first, there is n*2 vertices. If k is 1, we'll connect (i*2,(j+1)*2+1) and (i*2+1,(j+1)*2), if k is 0, we'll connect (i*2,(j+1)*2) and (i*2+1,(j+1)*2+1) (note that i<=j). If both i*2 and i*2+1 are in the same set for any i, the answer is 0. Otherwise the answer is 2^((the number of sets-2)/2).
|
[
"dsu",
"math"
] | 2,800
| null |
461
|
E
|
Appleman and a Game
|
Appleman and Toastman like games. Today they play a game with strings with the following rules. Firstly Toastman tells Appleman two strings $s$ and $t$ both consisting only of letters 'A', 'B', 'C', 'D'. Then Appleman must build string $s$ as quickly as possible. Initially he has empty string, and in one second he can append to end of the current string any contiguous substring of $t$.
Now, Toastman and Appleman are beginning to play the game. Toastman has already told string $t$ to Appleman, but he hasn't come up with string $s$ yet. Toastman only thinks, that he should choose string $s$ consisting of $n$ characters. Of course, he wants to find the worst string for Appleman (such string, that Appleman will spend as much time as possible during the game). Tell Toastman, how much time will Appleman spend during the game if Toastman finds the worst string for him. You can assume that Appleman plays optimally, therefore he builds any string $s$ in minimal possible time.
|
Let C be the number of characters(here, C=4) Given string S, the way to achieve minimum steps is as follows: Append one of the longest substring of T that fits current position of string S. Appending a not-longest substring can be replaced by appending longest substring and shortening the next substring appended. Let dp[K][c1][c2] be defined as : the minimum length of string that can be obtained by appending a string K times and that starts by character c1 and whose next character is c2. Note that next character is not counted in the length. dp[1] can be calculated as follows: For every string of length L expressed by C characters, if the string is not included in T, update the dp table as dp[1][the string's first character][its last character]=min(dp[1][its first character][its last character],L-1) For any (c1,c2), dp[1][c1][c2] is smaller than or equal to log_C(T+1)+2 (since the kind of strings of length log_C(T+1)+2 that start by c1 and end by c2 is equals to T+1). Therefore for L=1...log(T+1)+2, try all the strings as described above. Also we can use trie that contains all substrings of T of length log_C(T+1)+2, and find what can't be described as a substring of T by one step. Since dp[k+1][c1][c2]=min(dp[k][c1][c3]+dp[1][c3][c2] | c3=1...C), we can use matrix multiplication to get dp[K]. For a integer K, if there is (c1,c2) such that dp[K][c1][c2]<|S|, the answer is greater than K. Otherwise,the answer is smaller than or equal to K. Since answer is bigger or equal to 1 and smaller or equal to |S|, we can use binary search to find the ansewr. O(T*((log T)^2+C^2)+C^3(log |S|)^2)
|
[
"binary search",
"shortest paths",
"strings"
] | 3,000
| null |
462
|
A
|
Appleman and Easy Task
|
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a $n × n$ checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
|
This is a simple implementation problem. You can solve by searching adjacent cells of every cell.
|
[
"brute force",
"implementation"
] | 1,000
| null |
462
|
B
|
Appleman and Card Game
|
Appleman has $n$ cards. Each card has an uppercase letter written on it. Toastman must choose $k$ cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card $i$ you should calculate how much Toastman's cards have the letter equal to letter on $i$th, then sum up all these quantities, such a number of coins Appleman should give to Toastman.
Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
|
This is simple greedy problem, but it seemed to be reading-hard. The statement says, "Choose K cards from N cards, the score of each card is (the number of cards which has the same character in K cards. (not in N cards)" It is clear that this total score is (the number of 'A' in K cards)^2 + (the number of 'B' in K cards)^2 + ... + (the number of 'Z' in K cards)^2 This value will be maximized by the simple greedy algorithm, take K cards from most appearred character in N cards, the second most appearred character in N cards, and so on.
|
[
"greedy"
] | 1,300
| null |
463
|
A
|
Caisa and Sugar
|
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.
Unfortunately, he has just $s$ dollars for sugar. But that's not a reason to be sad, because there are $n$ types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed $99$, because each seller maximizes the number of dollars in the change ($100$ cents can be replaced with a dollar).
Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.
|
This is a simple implementation problem.
|
[
"brute force",
"implementation"
] | 1,200
|
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("date.in","r",stdin);
freopen("date.out","w",stdout);
#endif
int n, s;
cin.sync_with_stdio(false);
cin >> n >> s;
int sol = 100;
bool ok = 0;
for(int i = 1;i <= n; ++i){
int x, y;
cin >> x >> y;
if(x < s){
if(y)
sol = min(sol,y);
}
if(x < s || (x==s && y==0))
ok = 1;
}
if(!ok)
cout<<"-1\n";
else
cout<<100-sol<<"\n";
return 0;
}
|
463
|
B
|
Caisa and Pylons
|
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are $(n + 1)$ pylons numbered from $0$ to $n$ in this game. The pylon with number $0$ has zero height, the pylon with number $i$ $(i > 0)$ has height $h_{i}$. The goal of the game is to reach $n$-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as $k$) to the next one (its number will be $k + 1$). When the player have made such a move, its energy increases by $h_{k} - h_{k + 1}$ (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.
Initially Caisa stand at $0$ pylon and has $0$ energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?
|
We have to use greedy method. Start from the first element and pass all the elements in order(also update by the energy).When energy < 0, add abs(energy) to solution and energy becomes 0 or we can find the answer by binary search.
|
[
"brute force",
"implementation",
"math"
] | 1,100
|
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("date.in","r",stdin);
freopen("date.out","w",stdout);
#endif
int x = 0, y, n, sol = 0,energy = 0;
cin >> n;
for(int i = 1;i <= n; ++i)
{
cin >> y;
energy += x-y;
if(energy < 0){
sol += -energy;
energy = 0;
}
x = y;
}
cout<<sol<<"\n";
return 0;
}
|
463
|
C
|
Gargari and Bishops
|
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.
He has a $n × n$ chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number $x$ written on it, if this cell is attacked by one of the bishops Gargari will get $x$ dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.
We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).
|
We preprocess the sum for all the diagonals(principals and secondary diagonals) in two arrays(so that for every element $i$,$j$ we can find sum of elements which are attacked in O(1) time).Also for avoiding the intersection,we need to find two cells so that for one the sum of row and column is even and for the other one the sum of row and column is odd.Finally,we analyze every cell ,we see if the sum of row and column is even or odd,and update that two positions(solutions).
|
[
"greedy",
"hashing",
"implementation"
] | 1,900
|
#include <iostream>
#include <cstdio>
using namespace std;
const int NMAX = 2014;
long long d1[2*NMAX], d2[2*NMAX], sol[2];
pair < int , int > v[2];
int a[NMAX][NMAX];
inline void Update(const int c,const int i,const int j,const long long val){
if(val > sol[c]){
sol[c] = val;
v[c].first = i;
v[c].second = j;
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("date.in","r",stdin);
freopen("date.out","w",stdout);
#endif
cin.sync_with_stdio(false);
int n;
cin >> n;
sol[0] = sol[1] = -1;
for(int i = 1;i <= n; ++i)
for(int j = 1;j <= n; ++j){
int x;
cin >> a[i][j];
d1[i+j] += a[i][j];
d2[i-j+n] += a[i][j];
}
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
Update((i+j)&1,i,j,d1[i+j]+d2[i-j+n]-a[i][j]);
cout<<sol[0]+sol[1]<<"\n";
if(v[0] > v[1])
swap(v[0],v[1]);
cout<<v[0].first<<" "<<v[0].second<<" ";
cout<<v[1].first<<" "<<v[1].second<<"\n";
return 0;
}
|
463
|
D
|
Gargari and Permutations
|
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found $k$ permutations. Each of them consists of numbers $1, 2, ..., n$ in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?
You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
|
We can build a directed acyclic graph with $n$ nodes.If $j$ is after $i$ in all vectors then we add in graph edge ($i$,$j$).Now we have to find the longest path in this graph. Another way is using dp.
|
[
"dfs and similar",
"dp",
"graphs",
"implementation"
] | 1,900
|
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
const int NMAX = 1010;
int N, K, V[10][NMAX], Pos[10][NMAX], Best[NMAX], Ans;
vector<int> G[NMAX];
bool Used[NMAX];
void DFS(int Node)
{
Used[Node] = 1;
for(int i = 0; i < G[Node].size(); ++ i)
{
if(!Used[G[Node][i]])
DFS(G[Node][i]);
Best[Node] = max(Best[Node], Best[ G[Node][i] ] + 1);
}
Best[Node] = max(Best[Node], 1);
Ans = max(Ans, Best[Node]);
}
int main()
{
// freopen("d.in", "r", stdin);
// freopen("d.out", "w", stdout);
scanf("%i %i", &N, &K);
for(int i = 1; i <= K; ++ i)
for(int j = 1; j <= N; ++ j)
{
scanf("%i", &V[i][j]);
Pos[i][ V[i][j] ] = j;
}
for(int i = 1; i <= N; ++ i)
for(int j = 1; j <= N; ++ j)
{
if(i == j) continue;
bool OK = 1;
for(int k = 1; k <= K; ++ k)
if(Pos[k][i] >= Pos[k][j])
OK = 0;
if(OK) G[i].push_back(j);
}
for(int i = 1; i <= N; ++ i)
if(!Used[i])
DFS(i);
printf("%i\n", Ans);
}
|
463
|
E
|
Caisa and Tree
|
Caisa is now at home and his son has a simple task for him.
Given a rooted tree with $n$ vertices, numbered from $1$ to $n$ (vertex $1$ is the root). Each vertex of the tree has a value. You should answer $q$ queries. Each query is one of the following:
- Format of the query is "1 $v$". Let's write out the sequence of vertices along the path from the root to vertex $v$: $u_{1}, u_{2}, ..., u_{k}$ $(u_{1} = 1; u_{k} = v)$. You need to output such a vertex $u_{i}$ that $gcd(value of u_{i}, value of v) > 1$ and $i < k$. If there are several possible vertices $u_{i}$ pick the one with maximum value of $i$. If there is no such vertex output -1.
- Format of the query is "2 $v$ $w$". You must change the value of vertex $v$ to $w$.
You are given all the queries, help Caisa to solve the problem.
|
We use an array of dynamic stacks for every prime factor.We start a DFS from node 1.For node 1 we decompose its value in prime factors and push it to every prime factor's stack.To answer the question for $x$,we need to see the $y$ ($y$ belongs to the chain from 1 to $x$) that has a common prime factor with x,so the stacks will help us to see the earliest update(so the nearest $y$). For every $x$ ,we decompose $x$ to prime factors,look in the array and see the earliest update of the prime factors' stacks(if exists,of course). Also when we get back to fathers recursively,we need to pop from the prime factors' stacks. For every update we have to start dfs again.
|
[
"brute force",
"dfs and similar",
"math",
"number theory",
"trees"
] | 2,100
|
#include <vector>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <stack>
#include <bitset>
using namespace std;
const int NMAX = 100004;
const int VALMAX = 2e6;
vector < int > Tree[NMAX];
int value[NMAX], niv[NMAX] , answer[NMAX];
bitset < VALMAX+6> viz;
int prime[2*NMAX],pos[6+VALMAX];
stack < int > St[2*NMAX];
inline void Eratosthenes(){
prime[++prime[0]] = 2;
pos[2] = 1;
for(int i = 3;i <= VALMAX;i += 2)
if(!viz[i]){
prime[++prime[0]] = i;
pos[i] = prime[0];
for(long long j = 1LL*i*i;j <= VALMAX; j += 2*i)
viz[j] = 1;
}
}
inline void DFS(const int node,const int father){
vector < int > v;
int d = 2,step = 1;
int x = value[node];
answer[node] = 0;
while(d*d <= x){
if(x%d==0){
if(!St[pos[d]].empty()){
int y = St[pos[d]].top();
if(niv[y] > niv[answer[node]])
answer[node] = y;
}
v.push_back(pos[d]);
St[pos[d]].push(node);
while(x%d==0)
x /= d;
}
++step;
d = prime[step];
}
if(x > 1){
if(!St[pos[x]].empty()){
int y = St[pos[x]].top();
if(niv[y] > niv[answer[node]])
answer[node] = y;
}
v.push_back(pos[x]);
St[pos[x]].push(node);
}
for(vector < int > ::iterator it = Tree[node].begin(); it != Tree[node].end(); ++it)
if(*it!=father){
niv[*it] = niv[node] + 1;
DFS(*it,node);
}
for(vector < int > ::iterator it = v.begin(); it != v.end() ; ++it)
St[*it].pop();
v.clear();
}
int main(){
#ifndef ONLINE_JUDGE
freopen("date.in","r",stdin);
freopen("date.ok","w",stdout);
#endif
cin.sync_with_stdio(false);
Eratosthenes();
int n, m;
cin >> n >> m;
for(int i = 1;i <= n; ++i)
cin >> value[i];
for(int i = 1;i < n; ++i){
int x, y;
cin >> x >> y;
Tree[x].push_back(y);
Tree[y].push_back(x);
}
niv[1] = 1;
DFS(1,-1);
while(m--){
int operation, x, y;
cin >> operation >> x;
if(operation == 1){
if(answer[x] > 0)
cout<<answer[x]<<"\n";
else
cout<<"-1\n";
}
else{
cin >> y;
value[x] = y;
DFS(1,-1);
}
}
return 0;
}
|
464
|
A
|
No to Palindromes!
|
Paul \underline{hates} palindromes. He assumes that string $s$ is \underline{tolerable} if each its character is one of the first $p$ letters of the English alphabet and $s$ doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string $s$ of length $n$. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
|
If string $s$ contains a non-trivial palindromic substring $w$, then it must contain palindromic substring of length 2 or 3 (for instance, center of $w$). Therefore the string is tolerable iff no adjacent symbols or symbols at distance 1 are equal. Now for the lexicographically next tolerable string $t$. $t$ is greater than $s$, so they have common prefix of some size (maybe zero) and the next symbol is greater in $t$ than in $s$. This symbol should be as right as possible to obtain minimal possible $t$. For some position $i$ we can try to increment $s_{i}$ and ensure it's not equal to $s_{i - 1}$ or $s_{i - 2}$. If we find some way to do this, the suffix can always be filled correctly if only $p \ge 3$, as at most two symbols are forbidden at every moment. Every symbol from suffix should be as small as possible not to make conflicts. So, a greedy procedure or some kind of clever brute-force can be implemented to solve the problem in $O(n)$. Cases $p = 1$ or $2$ are easy, as only strings of length at most 1, and at most 2 respectively fit. This is an application on general approach to generate next lexicographical something: try to increment rightmost position so that suffix can be filled up in some way, then fill the suffix in least possible way.
|
[
"greedy",
"strings"
] | 1,700
| null |
464
|
B
|
Restore Cube
|
Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers \textbf{inside a single line} (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.
When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly.
|
There are several ways to solve this problem. We'll describe the most straightforward one: we can generate all possible permutations of coordinates of every point and for every combination check whether given point configuration form a cube. However, number of configurations can go up to $(3!)^{8} > 10^{6}$, so checking should work quite fast. One way to check if the points form a cube is such: find minimal distance between all pairs of points, it should be equal to the side length $l$. Every vertex should have exactly three other points at distance $l$, and all three edges should be pairwise perpendicular. If these condition are met at every point, then configuration is a cube as there is no way to construct another configuration with these properties. This procedure performs roughly $8^{2}$ operations for every check, which is fast enough. There are even more efficient ways of cube checking exploiting various properties of cube. There are various optimizations to ensure you fit into time limit. For instance, applying the same permutation to coordinates of all points keeps every property of the cube, therefore we can fix order of coordinates for one point and permute all other. This single trick speeds up the algorithm 6 times, which allows some less efficient programs to be accepted.
|
[
"brute force",
"geometry"
] | 2,000
| null |
464
|
C
|
Substitutes in Number
|
Andrew and Eugene are playing a game. Initially, Andrew has string $s$, consisting of digits. Eugene sends Andrew multiple queries of type "$d_{i} → t_{i}$", that means "replace all digits $d_{i}$ in string $s$ with substrings equal to $t_{i}$". For example, if $s = 123123$, then query "$2 → 00$" transforms $s$ to $10031003$, and query "$3 → $" ("replace 3 by an empty string") transforms it to $s = 1212$. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to $s$ by $1000000007 (10^{9} + 7)$. When you represent $s$ as a decimal number, please ignore the leading zeroes; also if $s$ is an empty string, then it's assumed that the number equals to zero.
Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!
|
It is quite diffcult to store the whole string after each query as its length grows exponentially and queries may change it dramatically. The good advice is: if you can't come up with a solution for a problem, try solving it from the other end. =) Suppose we know for some sequence of queries that digit $d$ will turn into string $t_{d}$ for every digit. Then string $s = d_{1}... d_{n}$ will turn into $t_{d1} + ... + t_{dn}$ (+ for concatenation). Denote $v(s)$ numeric value of $s$. Then $v(s)$ can be expressed as $v(t_{dn}) + 10^{|dn|}(v(t_{dn - 1}) + 10^{|dn - 1|}(...))$. So $v(s)$ can be computed if we know $m_{d} = v(t_{d})$ and $s_{d} = 10^{|td|}$ for all $d$. As we need answer modulo $P = 10^{9} + 7$ we can store these numbers modulo $P$. Now prepend some new query $d_{i} \rightarrow t_{i}$ to given sequence. How will $m_{d}$ and $s_{d}$ change? Clearly, for all $d \neq d_{i}$ these numbers won't change, and for $d_{i}$ they can be computed according to the rule above. This recounting is done in $O(|t_{i}|)$ time. After adding all queries, find answer for $s$ using the same procedure in $O(|s|)$ time. Finally, our time complexity is $O(|s|+\sum|t_{i}|)$. The code for this problem pretty much consists of the above formula, so implementation is as easy as it gets once you grasp the idea. =)
|
[
"dp"
] | 2,100
| null |
464
|
D
|
World of Darkraft - 2
|
Roma found a new character in the game "World of Darkraft - 2". In this game the character fights monsters, finds the more and more advanced stuff that lets him fight stronger monsters.
The character can equip himself with $k$ distinct types of items. Power of each item depends on its level (positive integer number). Initially the character has one $1$-level item of each of the $k$ types.
After the victory over the monster the character finds exactly one new randomly generated item. The generation process looks as follows. Firstly the type of the item is defined; each of the $k$ types has the same probability. Then the level of the new item is defined. Let's assume that the level of player's item of the chosen type is equal to $t$ at the moment. Level of the new item will be chosen uniformly among integers from segment [$1$; $t + 1$].
From the new item and the current player's item of the same type Roma chooses the best one (i.e. the one with greater level) and equips it (if both of them has the same level Roma choses any). The remaining item is sold for coins. Roma sells an item of level $x$ of any type for $x$ coins.
Help Roma determine the expected number of earned coins after the victory over $n$ monsters.
|
This problem required some skill at probabilities handling, but other than that it's quite simple too. Denote number of earned coins as $X$, and number of earned coins from selling items of type $i$ as $X_{i}$. Clearly $X = X_{1} + ... + X_{k}$, and $EX = EX_{1} + ... + EX_{k}$ (here $EX$ is expectation of $X$). As all types have equal probability of appearance, all $X_{i}$ are equal, so $EX = kEX_{1}$. Now to find $EX_{1}$. If we look only at the items of one type, say, 1, items generation looks like this: with probability $1-{\frac{1}{k}}$ we get nothing, and with probability $\textstyle{\frac{1}{k}}$ we get out item with level distributed as usual. Denote $d_{n, t}$ expectation of earned money after killing $n$ monsters if we have an item of level $t$ at the start. Clearly, $d_{0, t} = 0$ (we have no opportunity to earn any money), and $d_{n,t}=\frac{1}{k}\sum_{j=1}^{t+1}\frac{1}{t+1}(d_{n-1,m a x(j,t)}+m i n(j,t))+\frac{k-1}{k}d_{n-1,t}$, which is equal to ${\frac{1}{k(t+1)}}(t d_{n-1,t}+\sum_{j=1}^{t}j+d_{n-1,t+1}+t)+{\frac{k_{-1}}{k}}d_{n-1,t}$ = $\frac{1}{k(t+1)}(t d_{n-1,t}+d_{n-1,t+1}+t(t+3)/2)+\frac{k-1}{k}d_{n-1,t}$. To get the answer note that $EX_{1} = d_{n, 1}$. The sad note is that this DP has $ \Omega (n^{2})$ states, which is too much for $n\sim10^{5}$. Maybe if we cut off some extremely-low-probability cases we can do better? For instance, it is clear that probability of upgrading an item descreases with its level, so apparently it does not get very high. We know that expected number of tries before first happening of event with probability $p$ in a series of similar independent events is $1 / p$. Therefore, expected number of monsters we have to kill to get item of level $T$ is $2k+3k+\cdot\cdot\cdot+T k\sim k T^{2}/2$. So, in common case our level can get up to about $\sqrt{2n/k}$, which does not exceed $500$ in our limitations. We would want to set such bound $B$ that ignoring cases with $t > B$ would not influence our answer too much. That can be done with rigorous bounding of variance of $T$ and applying some bounding theorem, or with an empirical method: if we increase the bound and the answer doesn't visibly change, then this bound is fine. It turns out $B \ge 700$ is good enough for achieving demanded precision. Thus solution with $O(n{\sqrt{n}})$ complexity is obtained (here we assert that $B\sim C{\sqrt{n}}$, and constant $C$ is buried in the big O).
|
[
"dp",
"probabilities"
] | 2,700
| null |
464
|
E
|
The Classic Problem
|
You are given a weighted undirected graph on $n$ vertices and $m$ edges. Find the shortest path from vertex $s$ to vertex $t$ or else state that such path doesn't exist.
|
This seems to be a simple graph exercise, but the problem is with enormous weights of paths which we need to count and compare with absolute precision to get Dijkstra working. How do we do that? The fact that every edge weight is a power of two gives an idea that we can store binary representation of path value as it doesn't change much after appending one edge. However, storing representations explicitly for all vertices is too costly: the total number of 1's in them can reach $ \Omega (nd)$ ($d$ is for maximal $x_{i}$), which doesn't fit into memory even with bit compression woodoo magic. An advanced data structure is needed here which is efficient in both time and memory. The good choice is a persistent segment tree storing bit representation. Persistent segment tree is pretty much like the usual segment tree, except that when we want to change the state of some node we instead create a new node with links to children of old node. This way we have some sort of ''version control'' over tree: every old node is present and available for requests as its subtree can never change. Moreover, all queries are still processed in $O(\log n)$ time, but can create up to $O(\log n)$ new nodes. What queries do we need? Adding $2^{x}$ to binary number can be implemented as finding nearest most significant $0$ to $x$-th bit, setting it to $1$ and assigning $0$'s to all the positions in between. Usual segment tree with lazy propagation can do it, so persistent tree is able to do it as well. Comparing two numbers can be done as follows: find the most singificant bit which differs in two numbers, then number with $0$ in this bit is smaller; if no bits differ, then numbers are clearly equal. That can be done in $O(\log n)$ if we store hashes of some sort in every node and perform a parallel binary search on both trees. Time and memory limits were very generous so you could store as many different hashes as you wanted to avoid collisions. That concludes the general idea. Now we use this implementation of numbers as a black-box for Dijkstra algorithm. Every operation on numbers is now slowed by a factor of $O(\log d)$, so our solution has $O(m\log n\log d)$ complexity. However, great caution is needed to achieve a practical solution. First of all, in clueless implementation comparison of two "numbers" may require $O(\log d)$ additional memory as we must perform "push" operation as we descend. $O(m\log n\log d)$ memory is too much to fit even in our generous ML. There are plenty of ways to avoid this, for instance, if we want to push the value from node to children, we actually know that the whole segment consists of equal values and can answer the query right away. I would like to describe a clever trick which optimizes both time and memory greatly and also simplifies implementation. It allows to get rid of lazy propagation completely. Here it comes: initially build two trees containing only $0$'s and only $1$'s respectively. Now suppose we want to assign some value ($0$, for instance) on a segment and some tree node completely lies inside of query segment. Instead of creating a new node with a propagation mark, we can replace the node with corresponding node from tree filled with $0$. This way only $\sim\log d$ new nodes are created on every query (which is impossible to achieve with any kind of propagation which would require at least $\sim2\log d$), and also nodes need to store less information and become lighter this way. Also, no "push" procedure is required now.
|
[
"data structures",
"graphs",
"shortest paths"
] | 3,000
| null |
465
|
A
|
inc ARG
|
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of $n$ bits. These bits are numbered from $1$ to $n$. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the $n$-th bit.
Now Sergey wants to test the following instruction: "add $1$ to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.
Sergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?
|
If we add 1 to a number, its binary representation changes in a simple way: all the least significant $1$'s change to $0$'s, and the single following $0$ changes to $1$. It suffices to find the length of largest suffix which contains only $1$'s, suppose its length is $l$. Then the answer is $l + 1$ except for the case when all the string consists of $1$, when the answer is $l$.
|
[
"implementation"
] | 900
| null |
465
|
B
|
Inbox (100500)
|
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations:
- Move from the list of letters to the content of any single letter.
- Return to the list of letters from single letter viewing mode.
- In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.
The program cannot delete the letters from the list or rearrange them.
Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?
|
Optimal strategy is as follows: for every segment of consecutive $1$'s open the first letter in segment, scroll until the last letter in segment, if there are more unread letters left, return to list. It is easy to show that we can not do any better: observe the moment we read the last letter from some segment of consecutive $1$'s. There are no adjacent unread letters now, so we either have to scroll to some read letter or return to list of letters, either way we make an operation which does not result in reading an unread letter, so every segment (except for the last) must yield at least one such operation.
|
[
"implementation"
] | 1,000
| null |
466
|
A
|
Cheap Travel
|
Ann has recently started commuting by subway. We know that a one ride subway ticket costs $a$ rubles. Besides, Ann found out that she can buy a special ticket for $m$ rides (she can buy it several times). It costs $b$ rubles. Ann did the math; she will need to use subway $n$ times. Help Ann, tell her what is the minimum sum of money she will have to spend to make $n$ rides?
|
Solution of this problem is based on two claims: - If $m \cdot a \le b$ then there is no point to buy a ride ticket. - Sometimes it is better to buy summary more ride tickets for amount of rides than we need. If we receive profits bying ride tickets then number of such ones will be $x=\lfloor{\frac{n}{m}}\rfloor$. For the remain $n - m \cdot x$ rides we must choose the best variant: to buy separate ticket for each ride, or to buy ride ticket and use it not fully. Complexity: $O(1)$
|
[
"implementation"
] | 1,200
|
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, m, a, b;
cin >> n >> m >> a >> b;
if (m * a <= b)
cout << n * a << "\n";
else
cout << (n/m) * b + min((n%m) * a, b) << "\n";
return 0;
}
|
466
|
B
|
Wonder Room
|
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a $a × b$ square meter wonder room. The caretaker wants to accommodate exactly $n$ students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for $n$ students must have the area of at least $6n$ square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all $n$ students could live in it and the total area of the room was as small as possible.
|
Let's assume that $a \le b$. First of all, let's consider the situation when we can already accommodate all the students. If $6 \cdot n \le a \cdot b$ then answer is $a \cdot b$ $a$ $b$. Otherwise, we have to increase one of the walls(maybe, both). Let's do it in the following way: iterate the size of the smallest wall $new_{a}$ ($a\leq n e w_{a}\leq\left|{\sqrt{6\cdot n}}\right|$ ), after that we can calculate the size of another wall as $m e w_{b}=\textstyle\bigcap_{n e w a}^{6\cdots n}\N$. For all this $new_{a}$ and $new_{b}$ if $b \le new_{b}$ we choose such a pair that has the smallest area of a room. Obviously to undestrand, that there is no point to consider $n e w_{a}>\lceil{\sqrt{6\cdot n}}\rceil$ because we can decrease it and receive room of smaller area when we know that $6\cdot n\leq([{\sqrt{6\cdot n}}])^{2}\leq n e w_{a}\cdot n e w_{b}$. Complexity: $O({\sqrt{n}})$
|
[
"brute force",
"math"
] | 2,000
|
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(0);
long long n, a, b;
cin >> n >> a >> b;
if (6*n <= a*b)
cout << a*b << "\n" << a << " " << b << "\n";
else {
bool f = 0;
if (a > b)
{
swap(a, b);
f = 1;
}
long long SQ = 1e18, a1, b1, tmpb;
for(long long i = a; i*i <= 6*n; ++i) {
tmpb = 6*n / i;
if (tmpb * i < 6*n) tmpb++;
if (tmpb < b) continue;
if (tmpb * i < SQ) {
SQ = tmpb * i;
a1 = i;
b1 = tmpb;
}
}
if (f)
swap(a1, b1);
cout << SQ << "\n" << a1 << " " << b1 << "\n";
}
return 0;
}
|
466
|
C
|
Number of Ways
|
You've got array $a[1], a[2], ..., a[n]$, consisting of $n$ integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices $i, j$ $(2 ≤ i ≤ j ≤ n - 1)$, that $\sum_{k=1}^{i-1}a_{k}=\sum_{k=i}^{j}a_{k}$.
|
First of all, notice that if sum of all elements is equal $S$ then sum of each of three parts is equal $\frac{\mathrm{S}}{\mathrm{s}}$. Therefore, if $S$ is not divided by $3$ - then answer is $0$. Otherwise, let's iterate the end of first part $i$ ($1 \le i \le n - 2$) and if sum of 1..i elements is equal $\frac{\mathrm{S}}{\mathrm{s}}$ then it means that we have to add to the answer the amount of such $j$ ($i + 1 < j$) that the sum of elements from $j$-th to $n$-tn also equals $\frac{\mathrm{S}}{\mathrm{s}}$. Let's create an array cnt[], where $cnt[i]$ equals 1, if the sum of elements from $i$-th to $n$-th equals $\frac{\mathrm{S}}{\mathrm{s}}$ and 0 - otherwise. Now, to calculate the answer we have to find the sum cnt[j] + cnt[j+1] + ... + cnt[n] faster then O(n). There are a lot of required ways to do this, but the easiest one is to create a new additional array sums[] where in $j$-th element will be cnt[j] + cnt[j+1] + ... + cnt[n]. It is easy to calculate in such way: sums[n] = cnt[n], sums[i] = sums[i+1] + cnt[i] (i < n). Thus, we receive very simple solution: for each prefix of initial array 1..i with the sum that equals $\frac{\mathrm{S}}{\mathrm{s}}$ we need to add to the answer sums[i+2]. Complexity: $O(n)$
|
[
"binary search",
"brute force",
"data structures",
"dp",
"two pointers"
] | 1,700
|
#include <iostream>
#include <math.h>
using namespace std;
int a[1000010];
long long cnt[1000010];
int main()
{
ios::sync_with_stdio(0);
int n;
cin >> n;
long long s = 0;
for(int i = 0 ; i < n ; ++i)
{
cin >> a[i];
s += a[i];
}
if (s % 3 != 0)
cout << "0\n";
else {
s /= 3;
long long ss = 0;
for(int i = n-1; i >= 0 ; --i)
{
ss += a[i];
if (ss == s)
cnt[i] = 1;
}
for(int i = n-2 ; i >= 0 ; --i)
cnt[i] += cnt[i+1];
long long ans = 0;
ss = 0;
for(int i = 0 ; i+2 < n ; ++i) {
ss += a[i];
if (ss == s)
ans += cnt[i+2];
}
cout << ans << "\n";
}
return 0;
}
|
466
|
D
|
Increase Sequence
|
Peter has a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Peter wants all numbers in the sequence to equal $h$. He can perform the operation of "adding one on the segment $[l, r]$": add one to all elements of the sequence with indices from $l$ to $r$ (inclusive). At that, Peter never chooses any element as the beginning of the segment twice. Similarly, Peter never chooses any element as the end of the segment twice. In other words, for any two segments $[l_{1}, r_{1}]$ and $[l_{2}, r_{2}]$, where Peter added one, the following inequalities hold: $l_{1} ≠ l_{2}$ and $r_{1} ≠ r_{2}$.
How many distinct ways are there to make all numbers in the sequence equal $h$? Print this number of ways modulo $1000000007 (10^{9} + 7)$. Two ways are considered distinct if one of them has a segment that isn't in the other way.
|
Lets use dynamic programming to solve this problem. $dp[i][opened]$ - the number of ways to cover prefix of array 1..i by segments and make it equal to $h$ and remain after $i$-th element $opened$ segments that are not closed. Consider all possible variants opening/closing segments in each position: - ] closing one segment - [ opening one new segment - [] adding one segment with length 1 - ][ closing one opened segment and opening a new one - - do nothing Lets understand how to build dynamic. It is obviously to understand that $a[i] + opened$ can be equal $h$ or $h - 1$. Otherwise, number of such ways equals 0. Consider this two cases separately: 1) $a[i] + opened = h$ It means that number of opened segments after $i$-th as max as possible and we can't open one more segment in this place. So there are two variants: - [ Opening a new segment. If only $opened > 0$. dp[i][opened] += dp[i-1][opened + 1] - - Do nothing. dp[i][opened] += dp[i-1][opened] Other variants are impossible because of summary value of $a[i]$ will be greater than $h$(when segment is finishing in current position - it increase value, but do not influence on $opened$, by the dynamic definition. 2) $a[i] + opened + 1 = h$ Here we consider ways where $i$-th element has been increased by $opened + 1$ segments, but after $i$-th remain only $opened$ not closed segments. Therefore, there are next variants: - ] - closing one of the opened segments(we can do it $opened + 1$ ways). dp[i][opened] += dp[i-1][opened + 1] * (opened + 1) - [] - creating 1-length segment. dp[i][opened] += dp[i-1][opened] - ][ - If only $opened > 0$. Amount of ways to choose segment which we will close equals $opened$. dp[i][opened] += dp[i-1][opened] * opened Start values - dp[1][0] = (a[1] == h || a[1] + 1 == h?1:0); dp[1][1] = (a[1] + 1 == h?1:0) Answer - dp[n][0]. Complexity: $O(n)$
|
[
"combinatorics",
"dp"
] | 2,100
|
#include<iostream>
using namespace std;
#define MOD 1000000007
long long dp[2010][2010];
int a[2010];
inline void add(long long &a,long long b){
a += b;
a %= MOD;
}
int main()
{
ios_base::sync_with_stdio(0);
int n,h;
cin >> n >> h;
for (int i = 1; i <= n ;i ++)
cin >> a[i];
dp[1][0] = (a[1] == h || a[1] + 1 == h?1:0);
dp[1][1] = (a[1] + 1 == h?1:0);
for (int i = 2;i <= n + 1; i ++)
for (int open = max(0,h - a[i]- 1); open <= min(h - a[i],i) ; open ++){
if (a[i] + open == h){
add(dp[i][open] , dp[i - 1][open]);
if (open > 0)
add(dp[i][open] , dp[i - 1][open - 1]);
}
if (open + a[i] + 1 == h){
add(dp[i][open] , dp[i - 1][open + 1] * (open + 1));
add(dp[i][open] , dp[i - 1][open]);
add(dp[i][open] , dp[i - 1][open] * open);
}
}
cout << dp[n][0] << endl;
return 0;
}
|
466
|
E
|
Information Graph
|
There are $n$ employees working in company "X" (let's number them from 1 to $n$ for convenience). Initially the employees didn't have any relationships among each other. On each of $m$ next days one of the following events took place:
- either employee $y$ became the boss of employee $x$ (at that, employee $x$ didn't have a boss before);
- or employee $x$ gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive);
- or comes a request of type "determine whether employee $x$ signs certain documents".
Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies.
|
Let's introduce all structure of the company as a graph(if $y$ is the head of $x$ then we add edge $y$ -> $x$). It is obviously to understand that after each operation our graph will be the set of trees. Actually, the third query - to check is our vertex belong to the subtree of the vertex which has received data package. Graph that we will receive after doing all operations we call final. Also, we will say that two vertexes belong to the same connectivity component if they belong to the same component in graph that we can have from final by changing directed edge to undirected. Consider the following statement: vertex $y$ is the parent of vertex $x$ in current graph(after doing first $i$ queries) if $y$ and $x$ belongs to the same conectitive component and in final graph $y$ is the parent of $x$. We will solve this problem offline. After each query of adding data package we will immediately answer all the questions about this package. Besides that, use disjoint set union to define is this vertex belong to the same component or not. To answer the question we need to check that $y$ is the parent of $x$ in final graph and that $x$ and $y$ is currently belong to the same connectivity component. Final graph we will build before doing this algorithm because we know all queries. Check that $y$ is the parent of $x$ in final tree we can simply in O(1) by arrays of entry-time and output-time which we can calculate use dfs($v$ -parent $u$ <=> ($in[v] \le in[u]$ and $out[u] \le out[v]$). Complexity: $O(n * u(n))$, where $u$ - inverse Ackerman function.
|
[
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,100
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define MOD 1000000007
const int Nmax = 100100;
int QueryToNumber[Nmax] , NumberToQuery[Nmax];
int tin[Nmax], tout[Nmax], dsu[Nmax];
int Number = 0 , timer = 1 , n , m;
vector<vector<int> > g;
vector<int> Question[Nmax];
int deg[Nmax], answer[Nmax];
struct queries{
int t,x,y;
} List[Nmax];
void dfs(int v,int p = -1){
tin[v] = timer ++;
for (int i = 0 ;i < g[v].size(); i ++){
int u = g[v][i];
if (u == p) continue;
if (tin[u] == 0) dfs(u, v);
}
tout[v] = timer ++;
}
inline bool parent(int v,int u){
return (tin[v] <= tin[u] && tout[v] >= tout[u]);
}
int get(int v){
if (dsu[v] == v) return v;
return dsu[v] = get(dsu[v]);
}
void uni(int v,int u){
if (rand()% 2)
swap(v,u);
v = get(v),u = get(u);
dsu[v] = u;
}
int main()
{
ios_base::sync_with_stdio(0);
cin >> n >> m;
g.resize(n + 1);
for (int i = 1;i <= m ;i ++){
cin >> List[i].t;
if (List[i].t == 2) cin >> List[i].x;
else
cin >> List[i].x >> List[i].y;
if (List[i].t == 2)
QueryToNumber[i] = ++Number,
NumberToQuery[Number] = i;
if (List[i].t == 3)
Question[List[i].y].push_back(i);
}
for (int i = 1; i <= m ;i ++)
if (List[i].t == 1)
g[List[i].y].push_back(List[i].x),
deg[List[i].x] ++;
timer = 1;
for (int i = 1 ; i <= n ;i ++){
if (deg[i] != 0 || tin[i] != 0) continue;
dfs(i);
}
for (int i = 1; i <= n ; i ++)
dsu[i] = i;
for (int i = 1 ;i <= m ;i ++)
answer[i] = -1;
for (int i = 1; i <= m ;i ++){
if (List[i].t == 1){
uni(List[i].x,List[i].y);
continue;
}
if (List[i].t == 3) continue;
int num = QueryToNumber[i];
int v = List[i].x;
for (int j = 0 ;j < Question[num].size();j ++ ){
int u = List[Question[num][j]].x;
answer[Question[num][j]] = (get(v) == get(u) && parent(u,v));
}
}
for (int i = 1; i <= m ;i ++)
if (List[i].t == 3){
if (answer[i] == 1) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.