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
⌀ |
|---|---|---|---|---|---|---|---|
848
|
A
|
From Y to Y
|
From beginning till end, this message has been waiting to be conveyed.
For a given unordered multiset of $n$ lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length $1$, and repeat the following operation $n - 1$ times:
- Remove any two elements $s$ and $t$ from the set, and add their concatenation $s + t$ to the set.
The cost of such operation is defined to be $\sum_{c\in\{{\overset{*}{\scriptstyle a}}}{\overset{*}{\underset{}{v_{b}}},\dots*^{*}z}\cdot\}\,f\!\left(s,c\right)\cdot f\!\left(t,c\right)$, where $f(s, c)$ denotes the number of times character $c$ appears in string $s$.
Given a non-negative integer $k$, construct any valid non-empty set of no more than $100 000$ letters, such that the minimum accumulative cost of the whole process is \textbf{exactly} $k$. It can be shown that a solution always exists.
|
For a given string, how to calculate the cost? With several experiments, you may have found that the "minimum cost" doesn't make sense - the cost is always the same no matter how the characters are concatenated. Precisely, the cost of the process for a multiset of $c_{1}$ a's, $c_{2}$ b's, ... and $c_{26}$ z's, is $\textstyle\sum_{i=1}^{26}{\frac{1}{2}}\cdot c_{i}\cdot(c_{i}-1)$. It's in this form because every pair of same characters will contribute $1$ to the total cost. Therefore we need to find such $c_{1}, c_{2}, ..., c_{26}$ so that $\textstyle\sum_{i=1}^{26}{\frac{1}{2}}\cdot c_{i}\cdot\left(c_{i}-1\right)=k$. This can be done greedily and iteratively. Every time we subtract the maximum possible ${\frac{1}{2}}\cdot c\cdot(c-1)$ from $k$, and add $c$ same new letters to the set, until $k$ becomes $0$. This $c$ can be solved by any reasonable way, say quadratic formula, binary search or brute force. Time complexity veries from $O(\log^{2}k)$ to $O({\sqrt{k}}\log k)$ or any acceptable complexity, depending on the choice of the method for finding $c$. Of course, if a knapsack algorithm is used, it will use the minimum possible number of different letters, and works in $O(k{\sqrt{k}})$.
|
[
"constructive algorithms"
] | 1,600
|
#include <cstdio>
#include <vector>
static const int MAXK = 100002;
static const int INF = 0x3fffffff;
int f[MAXK];
int pred[MAXK];
int main()
{
f[0] = 0;
for (int i = 1; i < MAXK; ++i) f[i] = INF;
for (int i = 0; i < MAXK; ++i) pred[i] = -1;
for (int i = 0; i < MAXK; ++i) if (f[i] != INF) {
for (int j = 2; i + j * (j - 1) / 2 < MAXK; ++j)
if (f[i + j * (j - 1) / 2] > f[i] + 1) {
f[i + j * (j - 1) / 2] = f[i] + 1;
pred[i + j * (j - 1) / 2] = j;
}
} else printf("Assertion failed at %d\n", i);
int k;
scanf("%d", &k);
if (k == 0) { puts("a"); return 0; }
std::vector<int> v;
for (; k > 0; k -= pred[k] * (pred[k] - 1) / 2) {
v.push_back(pred[k]);
}
for (int i = 0; i < v.size(); ++i) {
for (int j = 0; j < v[i]; ++j) putchar('a' + i);
}
putchar('\n');
return 0;
}
|
848
|
B
|
Rooter's Song
|
Wherever the destination is, whoever we meet, let's render this song together.
On a Cartesian coordinate plane lies a rectangular stage of size $w × h$, represented by a rectangle with corners $(0, 0)$, $(w, 0)$, $(w, h)$ and $(0, h)$. It can be seen that no collisions will happen before one enters the stage.
On the sides of the stage stand $n$ dancers. The $i$-th of them falls into one of the following groups:
- \textbf{Vertical}: stands at $(x_{i}, 0)$, moves in positive $y$ direction (upwards);
- \textbf{Horizontal}: stands at $(0, y_{i})$, moves in positive $x$ direction (rightwards).
According to choreography, the $i$-th dancer should stand still for the first $t_{i}$ milliseconds, and then start moving in the specified direction at $1$ unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.
When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on.
Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.
|
How to deal with "waiting time"? Move every dancer $t_{i}$ units backwards in the first place, that is to $(x_{i} - t_{i}, 0)$ for the vertical-moving group, and $(0, y_{i} - t_{i})$ for the horizontal-moving group. Then start the time, making everyone start moving immediately. When do dancers collide? What changes and what keeps the same? Notice that if two dancers collide before any other collision happens, then they have the same $x + y$ values for their initial positions. Furthermore, after a collision, the two dancers keep having the same $x + y$, and also with the same relative orders of $x$ and $y$. Also, after a collision, the union of all dancers' tracks will be the same as if they "went through" each other and no collision happened at all (see the figure for sample 1 to get a general idea on this). Therefore, divide dancers into groups by $p_{i} - t_{i}$, and collisions will happen within groups only. Dancers in the same group will move on the same $x + y$ line (a line of slope $- 1$), and however collisions take place, they will keep current relative order of $x$ and $y$. It's proved before that in each group, dancers' exiting positions is the same as if no collision happened at all (namely, $(x_{i}, h)$ for initially-vertical dancers, and $(w, y_{i})$ for initially-horizontal ones). For each group, find out all such positions. Sort all dancers according to their initial $x$ values, and sort these positions in the direction of $(0, h)$ to $(w, h)$ then $(w, 0)$. Match the sorted dancers to these sorted positions and obtain the answers for all dancers. This solution works in $O(n\log n)$.
|
[
"constructive algorithms",
"data structures",
"geometry",
"implementation",
"sortings",
"two pointers"
] | 1,900
|
#include <cstdio>
#include <algorithm>
#include <vector>
static const int MAXN = 100004;
static const int MAXW = 100003;
static const int MAXT = 100002;
int n, w, h;
int g[MAXN], p[MAXN], t[MAXN];
std::vector<int> s[MAXW + MAXT];
int ans_x[MAXN], ans_y[MAXN];
int main()
{
scanf("%d%d%d", &n, &w, &h);
for (int i = 0; i < n; ++i) {
scanf("%d%d%d", &g[i], &p[i], &t[i]);
s[p[i] - t[i] + MAXT].push_back(i);
}
std::vector<int> xs, ys;
for (int i = 0; i < MAXW + MAXT; ++i) if (!s[i].empty()) {
for (int u : s[i]) {
if (g[u] == 1) xs.push_back(p[u]);
else ys.push_back(p[u]);
}
std::sort(xs.begin(), xs.end());
std::sort(ys.begin(), ys.end());
std::sort(s[i].begin(), s[i].end(), [] (int u, int v) {
if (g[u] != g[v]) return (g[u] == 2);
else return (g[u] == 2 ? p[u] > p[v] : p[u] < p[v]);
});
for (int j = 0; j < xs.size(); ++j) {
ans_x[s[i][j]] = xs[j];
ans_y[s[i][j]] = h;
}
for (int j = 0; j < ys.size(); ++j) {
ans_x[s[i][j + xs.size()]] = w;
ans_y[s[i][j + xs.size()]] = ys[ys.size() - j - 1];
}
xs.clear();
ys.clear();
}
for (int i = 0; i < n; ++i) printf("%d %d\n", ans_x[i], ans_y[i]);
return 0;
}
|
848
|
C
|
Goodbye Souvenir
|
I won't feel lonely, nor will I be sorrowful... not before everything is buried.
A string of $n$ beads is left as the message of leaving. The beads are numbered from $1$ to $n$ from left to right, each having a shape numbered by integers between $1$ and $n$ inclusive. Some beads may have the same shapes.
The \underline{memory} of a shape $x$ in a certain subsegment of beads, is defined to be the difference between the last position and the first position that shape $x$ appears in the segment. The \underline{memory} of a subsegment is the sum of \underline{memories} over all shapes that occur in it.
From time to time, shapes of beads change as well as the \underline{memories}. Sometimes, the past secreted in subsegments are being recalled, and you are to find the \underline{memory} for each of them.
|
Let's look at segment $[l, r]$. Let's $p_{1}^{x} < p_{2}^{x} < ... < p_{k}^{x}$ - positions of all occurences of shape $x$ at segment $[l, r]$. Then memory of shape $x$ at segment $[l, r]$ is $p_{k}^{x} - p_{1}^{x} = (p_{k}^{x} - p_{k - 1}^{x}) + (p_{k - 1}^{x} - p_{k - 2}^{x}) + ... + (p_{2}^{x} - p_{1}^{x})$. Then we can build array of pairs $b$: $b_{i} = (prev(i), i - prev(i))$, where $prev(i)$ - previous occurence of shape $a_{i}$ $(p r e v(i)=\operatorname*{max}_{a_{i}=a_{i}}j)$. A query transforms to: $\sum_{i\leq i\leq r\leq i}b_{i}.s e c o n d$, which is variation of counting numbers of greater on segment. Queries of change in position can be proccessed by recounting values $prev(p)$ for $a_{p}$ and next occurence of that shape before and after changing shape. Processing of all queries can be done by building segment tree, which every node contains Fenwick tree by types of shape. For reducing memory usage we can, for every node, save only shapes, which appeared in any query for this node. Then Fenwick tree can be build only on this shapes by coordinate compressing. Result complexity - $O(n \cdot log^{2}(n))$.
|
[
"data structures",
"divide and conquer"
] | 2,600
|
#include <bits/stdc++.h>
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) fore(i, 0, n)
#define all(a) (a).begin(), (a).end()
#define sqr(a) ((a) * (a))
#define sz(a) int(a.size())
#define mp make_pair
#define pb push_back
#define x first
#define y second
using namespace std;
template<class A, class B> ostream& operator << (ostream &out, const pair<A, B> &p) {
return out << "(" << p.first << ", " << p.second << ")";
}
template<class A> ostream& operator << (ostream &out, const vector<A> &v) {
out << "[";
forn(i, sz(v)) {
if(i > 0)
out << " ";
out << v[i];
}
return out << "]";
}
mt19937 myRand(time(NULL));
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
inline int gett() {
return clock() * 1000 / CLOCKS_PER_SEC;
}
const ld EPS = 1e-9;
const int INF = int(1e9);
const li INF64 = li(INF) * INF;
const ld PI = 3.1415926535897932384626433832795;
const int N = 100 * 1000 + 555;
int n, m, aa[N], a[N];
int qt[N], qx[N], qy[N];
inline bool read() {
if(!(cin >> n >> m))
return false;
forn(i, n)
assert(scanf("%d", &aa[i]) == 1);
forn(i, m) {
assert(scanf("%d%d%d", &qt[i], &qx[i], &qy[i]) == 3);
qx[i]--;
}
return true;
}
vector<int> vars[4 * N];
vector<li> f[4 * N];
li sumAll[4 * N];
inline void addValF(int k, int pos, int val) {
sumAll[k] += val;
for(; pos < sz(f[k]); pos |= pos + 1)
f[k][pos] += val;
}
inline li sum(int k, int pos) {
li ans = 0;
for(; pos >= 0; pos = (pos & (pos + 1)) - 1)
ans += f[k][pos];
return ans;
}
inline li getSumF(int k, int pos) {
return sumAll[k] - sum(k, pos - 1);
}
li getSumST(int v, int l, int r, int lf, int rg, int val) {
if(l >= r || lf >= rg)
return 0;
if(l == lf && r == rg) {
int pos = int(lower_bound(all(vars[v]), val) - vars[v].begin());
return getSumF(v, pos);
}
int mid = (l + r) >> 1;
li ans = 0;
if(lf < mid)
ans += getSumST(2 * v + 1, l, mid, lf, min(mid, rg), val);
if(rg > mid)
ans += getSumST(2 * v + 2, mid, r, max(lf, mid), rg, val);
return ans;
}
void addValST(int k, int v, int l, int r, int pos, int pos2, int val) {
if(l >= r)
return;
if(!k)
vars[v].pb(pos2);
else {
int cpos = int(lower_bound(all(vars[v]), pos2) - vars[v].begin());
addValF(v, cpos, val);
}
if(l + 1 == r) {
assert(l == pos);
return;
}
int mid = (l + r) >> 1;
if(pos < mid)
addValST(k, 2 * v + 1, l, mid, pos, pos2, val);
else
addValST(k, 2 * v + 2, mid, r, pos, pos2, val);
}
int pr[N];
set<int> ids[N];
void build(int k, int v, int l, int r) {
fore(i, l, r)
if(!k)
vars[v].pb(pr[i]);
else {
int pos = int(lower_bound(all(vars[v]), pr[i]) - vars[v].begin());
addValF(v, pos, i - pr[i]);
}
if(l + 1 == r)
return;
int mid = (l + r) >> 1;
build(k, 2 * v + 1, l, mid);
build(k, 2 * v + 2, mid, r);
}
inline void eraseSets(int k, int pos) {
addValST(k, 0, 0, n, pos, pr[pos], -(pos - pr[pos]));
ids[ a[pos] ].erase(pos);
auto it2 = ids[ a[pos] ].lower_bound(pos);
if(it2 != ids[ a[pos] ].end()) {
int np = *it2;
assert(a[np] == a[pos]);
assert(pr[np] == pos);
addValST(k, 0, 0, n, np, pr[np], -(np - pr[np]));
pr[np] = pr[pos];
addValST(k, 0, 0, n, np, pr[np], +(np - pr[np]));
}
a[pos] = -1;
pr[pos] = -1;
}
inline void insertSets(int k, int pos, int nval) {
auto it2 = ids[nval].lower_bound(pos);
assert(it2 == ids[nval].end() || *it2 > pos);
if(it2 != ids[nval].end()) {
int np = *it2;
assert(a[np] == nval);
addValST(k, 0, 0, n, np, pr[np], -(np - pr[np]));
pr[np] = pos;
addValST(k, 0, 0, n, np, pr[np], +(np - pr[np]));
}
pr[pos] = -1;
if(it2 != ids[nval].begin()) {
auto it1 = it2; it1--;
assert(*it1 < pos);
pr[pos] = *it1;
}
addValST(k, 0, 0, n, pos, pr[pos], +(pos - pr[pos]));
ids[nval].insert(pos);
a[pos] = nval;
}
inline void precalc() {
forn(v, 4 * N) {
sort(all(vars[v]));
vars[v].erase(unique(all(vars[v])), vars[v].end());
f[v].assign(sz(vars[v]), 0);
sumAll[v] = 0;
}
}
inline void solve() {
forn(k, 2) {
if(k) precalc();
forn(i, N)
ids[i].clear();
forn(i, n)
a[i] = aa[i];
vector<int> ls(n + 1, -1);
forn(i, n) {
pr[i] = ls[ a[i] ];
ls[ a[i] ] = i;
ids[ a[i] ].insert(i);
}
build(k, 0, 0, n);
// cerr << k << " " << clock() << endl;
forn(q, m) {
if(qt[q] == 1) {
eraseSets(k, qx[q]);
insertSets(k, qx[q], qy[q]);
} else
if(k) printf("%I64d\n", getSumST(0, 0, n, qx[q], qy[q], qx[q]));
}
// cerr << k << " " << clock() << endl;
}
}
int main(){
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int t = gett();
#endif
srand(time(NULL));
cout << fixed << setprecision(10);
while(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << gett() - t << endl;
t = gett();
#endif
}
return 0;
}
|
848
|
D
|
Shake It!
|
A never-ending, fast-changing and dream-like world unfolds, as the secret door opens.
A \underline{world} is an unordered graph $G$, in whose vertex set $V(G)$ there are two special vertices $s(G)$ and $t(G)$. An \underline{initial world} has vertex set ${s(G), t(G)}$ and an edge between them.
A total of $n$ changes took place in an \underline{initial world}. In each change, a new vertex $w$ is added into $V(G)$, \textbf{an existing edge} $(u, v)$ is chosen, and two edges $(u, w)$ and $(v, w)$ are added into $E(G)$. Note that it's possible that some edges are chosen in more than one change.
It's known that the capacity of the minimum $s$-$t$ cut of the resulting graph is $m$, that is, at least $m$ edges need to be removed in order to make $s(G)$ and $t(G)$ disconnected.
Count the number of non-similar worlds that can be built under the constraints, modulo $10^{9} + 7$. We define two \underline{worlds} similar, if they are isomorphic and there is isomorphism in which the $s$ and $t$ vertices are not relabelled. Formally, two \underline{worlds} $G$ and $H$ are considered similar, if there is a bijection between their vertex sets $f:V(G)\rightarrow V(H)$, such that:
- $f(s(G)) = s(H)$;
- $f(t(G)) = t(H)$;
- Two vertices $u$ and $v$ of $G$ are adjacent in $G$ if and only if $f(u)$ and $f(v)$ are adjacent in $H$.
|
Use DP. Let's try to find "subproblems" in this. A graph can be expressed as: an edge, in parallel with an unordered multiset of zero or more ordered pair of two graphs. That is, "graph = edge [// (graph + graph) [// (graph + graph) [...]]]". A graph can be represented by two parameters: number of operations needed to build it, and its minimum cut. Let $f[i][j]$ keep the number of graphs with $i$ operations and a minimum cut of $j$. The figure below shows one of the ways in which $f[8][5]$ can be built from other $f$'s. How to iterate over all such possible splitting into pairs, while keeping them unordered? One way is to iterate through pairs - instead of determining $f$'s one by one, we find all pairs of graph parameters and add them to graphs already formed with pairs considered before. (This is like how we do it in knapsack problems.) Iterate through the parameters of two graphs in a pair, $(a, b, c, d)$, and use a push-style transition to add each $f[i][j]$ into the corresponding state if the pair is added a number of times to a graph in $f[i][j]$. That is, for each $t$, add $f[i][j]\times\mathrm{MultiCombination}(f[a][b]\cdot f[c][d],t)$ to $f[i + t \cdot (a + c + 1)][j + t \cdot min(b, d)]$ - this means a pair of graphs with parameters $[a][b]$ and $[c][d]$ is added $t$ times to a graph with parameters $[i][j]$. With $O(n^{4})$ such parameters we need to spend $O(n^{2})$ time updating all values, therefore time complexity is $O(n^{6})$ which is not sufficient to pass. Note: MultiCombination($n$, $r$) means number of ways to select an unordered multiset of $r$ elements out of $n$ distinct elements, where one element can be selected more than once. This equals to $\textstyle{\binom{n+r-1}{r}}$. Let's see the pair as a whole. Let $g[i][j]$ keep the number of ordered graph pairs with $i$ operations and a minimum cut of $j$. At each step, in stead of iterating over four parameters of a pair, we iterate over two parameters and use values of $g$ to perform the update. It can be seen that $f[i][j]$ and $g[i][j]$ only depend on such $f[p][q]$ and $g[p][q]$ that $p \le i - 1$. Therefore, we can determine $f$ and $g$ values in order of increasing $i$. This solution works with $O(n^{2})$ states, each of which can be calculated in $O(n^{3})$ time with another $O(n)$ factor for MultiCombination, but since a harmonic series exists in the iteration of $t$, this is actually $O(n^{5}\log{n})$. Author's implementation takes a bit lower than 800 milliseconds to find an answer. If MultiCombination is calculated along with the iteration of $t$ (see the model solution), this works in $O(n^{4}\log{n})$ which is much faster. Bonus. Come up with a DP on dual graphs.
|
[
"combinatorics",
"dp",
"flows",
"graphs"
] | 2,900
|
#include <cstdio>
#include <cstring>
typedef long long int64;
static const int MAXN = 53;
static const int MODULUS = 1e9 + 7;
#define _ % MODULUS
#define __ %= MODULUS
int n, m;
// f[# of operations][mincut] -- total number of graphs
// g[# of operations][mincut] -- number of ordered pairs of two graphs
int64 f[MAXN][MAXN] = {{ 0 }}, g[MAXN][MAXN] = {{ 0 }};
int64 h[MAXN][MAXN];
inline int64 qpow(int64 base, int exp) {
int64 ans = 1;
for (; exp; exp >>= 1, (base *= base)__) if (exp & 1) (ans *= base)__;
return ans;
}
int64 inv[MAXN];
int main()
{
for (int i = 0; i < MAXN; ++i) inv[i] = qpow(i, MODULUS - 2);
scanf("%d%d", &n, &m);
f[0][1] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= i + 1; ++j) {
// Calculate g[i][*]
// pair(i)(j) = graph(p)(r) in series with graph(q)(s)
// where p+q == i-1, min(r, s) == j
for (int p = 0; p <= i - 1; ++p) {
int q = i - 1 - p;
for (int r = j; r <= p + 1; ++r)
(g[i][j] += (int64)f[p][r] * f[q][j])__;
for (int s = j + 1; s <= q + 1; ++s)
(g[i][j] += (int64)f[p][j] * f[q][s])__;
}
// Update all f with g[i][*]
// Iterate over the number of times pair(i)(j) is appended in parallel, let it be t
// h is used as a temporary array
memset(h, 0, sizeof h);
for (int p = 0; p <= n; ++p)
for (int q = 1; q <= p + 1; ++q) {
int64 comb = 1;
for (int t = 1; p + t * i <= n; ++t) {
comb = comb * (g[i][j] + t - 1)_ * inv[t]_;
(h[p + t * i][q + t * j] += f[p][q] * comb)__;
}
}
for (int p = 0; p <= n; ++p)
for (int q = 1; q <= p + 1; ++q)
(f[p][q] += h[p][q])__;
}
}
printf("%lld\n", f[n][m]);
return 0;
}
|
848
|
E
|
Days of Floral Colours
|
The Floral Clock has been standing by the side of Mirror Lake for years. Though unable to keep time, it reminds people of the passage of time and the good old days.
On the rim of the Floral Clock are $2n$ flowers, numbered from $1$ to $2n$ clockwise, each of which has a colour among all $n$ possible ones. For each colour, there are exactly two flowers with it, the \underline{distance} between which \textbf{either is less than or equal to $2$, or equals $n$}. Additionally, if flowers $u$ and $v$ are of the same colour, then flowers opposite to $u$ and opposite to $v$ should be of the same colour as well — symmetry is beautiful!
Formally, the \underline{distance} between two flowers is $1$ plus the number of flowers on the minor arc (or semicircle) between them. Below is a possible arrangement with $n = 6$ that cover all possibilities.
The \underline{beauty} of an arrangement is defined to be the product of the lengths of flower segments separated by all opposite flowers of the same colour. In other words, in order to compute the beauty, we remove from the circle all flowers that have the same colour as flowers opposite to them. Then, the beauty is the product of lengths of all remaining segments. Note that we include segments of length $0$ in this product. If there are no flowers that have the same colour as flower opposite to them, the beauty equals $0$. For instance, the \underline{beauty} of the above arrangement equals $1 × 3 × 1 × 3 = 9$ — the segments are ${2}$, ${4, 5, 6}$, ${8}$ and ${10, 11, 12}$.
While keeping the constraints satisfied, there may be lots of different arrangements. Find out the sum of \underline{beauty} over all possible arrangements, modulo $998 244 353$. Two arrangements are considered different, if a pair $(u, v)$ ($1 ≤ u, v ≤ 2n$) exists such that flowers $u$ and $v$ are of the same colour in one of them, but not in the other.
|
tl;dr Just look at recurrences of $g$, $f_{0}$, $f_{1}$ and $f_{2}$ and the part after $f_{2}$'s recurrence. Break the circle down into semicircles. We're basically pairing flowers under the restrictions. It's hard to deal with the whole circle, let's consider something simpler. Consider an arc of length $i$ (segment of $i$ flowers) and their opposite counterparts, surrounded by another two pairs of opposite flowers of the same colour. We will calculate their contribution to the total beauty, $f_{0}(i)$ - in other words, the total beauty if only this segment is required to be coloured (we will not pair them with flowers out of this segment). A such segment with $i = 7$. For clarity's sake, a flower's opposite counterpart is drawn directly below it. A such segment with $i = 7$. For clarity's sake, a flower's opposite counterpart is drawn directly below it. We come up with a function $g(i)$, denoting the number of ways to colour a segment of length $i$ with pairs of opposite $1$ and $2$ only. The recurrence is $g(0) = 1, g(1) = 0, g(i) = g(i - 2) + g(i - 4)$. First case: there are no opposite pairs within this segment. There are $g(i)$ ways to do this, giving a total beauty of $g(i) \cdot i^{2}$. Second case: there is at least one opposite pair within this segment. Fix the position of the first opposite pair, $j$ (in the range of $0$ and $i - 1$ inclusive). Another two cases diverge. (a) No pair of distance $2$ crosses the flowers at position $j$. In this case, a subproblem of length $i - j - 1$ emerge, generating a total beauty of $g(j) \cdot j^{2} \times f_{0}(i - j - 1)$. (b) A pair of distance $2$ crosses the flowers at position $j$. In this case, new subproblems appear - an arc of length $i - j - 2$ and their opposite counterparts, surrounded by an opposite same-colour pair on one side, and an already-paired flower and an opposite same-colour pair on the other. Denote this subproblem as $f_{1}$, this case generates a total beauty of $g(j - 1) \cdot j^{2} \times f_{1}(i - j - 3)$. Summing up and simplifying a bit, we get the recurrence for $f_{0}$: $\begin{array}{c}{{f_{0}(i)=g(i)\cdot i^{2}}}\\ {{\mathrm{}\ \!=\!\sum_{j=0}^{i-1}g(j)\cdot j^{2}\times f_{0}(i-j-1)}}\\ {{\mathrm{}\displaystyle\prod_{i=0}^{i-3}g(j)\cdot(j+1)^{2}\times f_{1}(i-j-3)}}\end{array}$ Doing almost the same (fix the opposite pair nearest to the side of an already-paired flower), we get the recurrence for $f_{1}$: $\begin{array}{c}{{f_{1}(i)=g(i)\cdot(i+1)^{2}}}\\ {{\mathrm{~}\!\!\!\!\!}}\\ {{\mathrm{~}\!\!\!\!\!}}\\ {{\mathrm{~}\!\!\!\!}}&{{\!\!\!}}\\ {{\mathrm{~}\!\!\!\!}}\\ {{\mathrm{~}\!\!\!\!}}&{{\!\!\!}}\\ {{\mathrm{~}\!\!\!\!\!}}\\ {{\mathrm{~}\!\!\!}^{{}\!\!\!\!\!}\!\!\!\!}}\\ {{\mathrm{~}\!\!\!\!}^{{\textstyle\frac{i-3}{i=0}g(j)\cdot(j+1)^{2}\times f_{0}(i-j-3)}}\end{array}$ Now we've solved the subproblem for a subsegment. Hooray! For the whole circle, let's fix a pair of opposite flowers. Let it be flowers $1$ and $n$. This can be rotated to generate other arrangements. But we don't know how many times it can be rotated without duplication. So we fix the second opposite pair, letting it be the first one starting from flower number $2$ and going clockwise. Let its position be $i$, then there shouldn't be any opposite pairs within $[2, i - 1]$, and all arrangements can be rotated in $j - 1$ different ways to generate all different arrangements. Example with $n = 9$ and $i = 5$. Example with $n = 9$ and $i = 5$. There may be or may be not pairs of distance $2$ crossing over flowers $1$ and $i$. Consider all four cases, we run into another subproblem with deja vu. We introduce a new function, $f_{2}(i)$, denoting the total beauty of a segment of length $i$, with an already-paired flower and an opposite same-colour pair on both sides. A subproblem of length $5$. A subproblem of length $5$. Following the method above, we get $\begin{array}{c}{{f_{2}(i)=g(i)\cdot(i+2)^{2}}}\\ {{\mathrm{~}\!\!\!\!\!\!}}\\ {{\mathrm{~}\!\!\!\!}}\\ {{\mathrm{~}\!\!\!\!}}&{{\!\!\!}}\\ {{\mathrm{~}\!\!\!\!}}\\ {{\mathrm{~}\!\!\!}}&{{\!\!\!\!}}\\ {{\mathrm{~}\!\!\!\!\!}}\\ {{\mathrm{~}\!\!\!}}&{{\!\!\!\!}}\end{array}$ Then the answer can be calculated in linear time, with $g$, $f_{0}$, $f_{1}$ and $f_{2}$ all calculated beforehand. Overall complexity is $O(n^{2})$. Refer to the square-time solution below for an implementation. Then, note that recurrences of $f_{0}$, $f_{1}$ and $f_{2}$ are in the form of convolutions, so we'd like to optimize it with FFT. However, they include convolutions of the previous parts of the function itself, with another function like $g(i) \cdot i^{2}$, $g(i) \cdot (i + 1)^{2}$ or $g(i) \cdot (i + 2)^{2}$. Under this situation, apply FFT in a divide-and-conquer subroutine. solve(L, R) assumes that $f(1;L - 1)$ are already calculated, and all the terms that contribute to $f(L;R)$ and involve $f(1;L - 1)$ are already accumulated in their corresponding array positions. It finishes calculation of $f(L;R)$. First, it calls solve(L, M), then add all terms that contribute to $f(M + 1;R)$ involving $f(L;M)$ by convolving $f(L;M)$ with the other function (say $g(i) \times i^{2}$), then call solve(M+1, R). Over complexity is $O(n\log^{2}n)$. The model solution solves $f_{0}$ and $f_{1}$ in one pass, and $f_{2}$ in another. They can also be merged into a single pass. Big thanks to you for patiently reading till this point, and if you just want to enjoy the problem rather than implementation, feel free just to write a $O(n^{2})$ solution :)
|
[
"combinatorics",
"divide and conquer",
"dp",
"fft",
"math"
] | 3,400
|
#include <cstdio>
#include <cstring>
typedef long long int64;
static const int LOGN = 18;
static const int MAXN = 1 << LOGN;
static const int MODULUS = 998244353;
static const int PRIMITIVE = 2192;
#define _ % MODULUS
#define __ %= MODULUS
template <typename T> inline void swap(T &a, T &b) { static T t; t = a; a = b; b = t; }
int n;
int64 g[MAXN];
int64 g0[MAXN], g1[MAXN], g2[MAXN];
int64 f0[MAXN], f1[MAXN], f2[MAXN];
int64 q0[MAXN], q1[MAXN];
int64 t1[MAXN], t2[MAXN], t3[MAXN], t4[MAXN];
inline int qpow(int64 base, int exp)
{
int64 ans = 1;
for (; exp; exp >>= 1) { if (exp & 1) (ans *= base)__; (base *= base)__; }
return ans;
}
int bitrev[LOGN][MAXN];
int root[2][LOGN];
inline void fft(int n, int64 *a, int direction)
{
int s = __builtin_ctz(n);
int64 u, v, r, w;
for (int i = 0; i < n; ++i) if (i < bitrev[s][i]) swap(a[i], a[bitrev[s][i]]);
for (int i = 1; i <= n; i <<= 1)
for (int j = 0; j < n; j += i) {
r = root[direction == -1][__builtin_ctz(i)];
w = 1;
for (int k = j; k < j + (i >> 1); ++k) {
u = a[k];
v = (a[k + (i >> 1)] * w)_;
a[k] = (u + v)_;
a[k + (i >> 1)] = (u - v + MODULUS)_;
w = (w * r)_;
}
}
}
inline void convolve(int n, int64 *a, int64 *b, int64 *c)
{
static int64 a1[MAXN], b1[MAXN];
memcpy(a1, a, n * 2 * sizeof(int64));
memcpy(b1, b, n * 2 * sizeof(int64));
memset(a + n, 0, n * sizeof(int64));
memset(b + n, 0, n * sizeof(int64));
fft(n * 2, a, +1);
fft(n * 2, b, +1);
int64 q = qpow(n * 2, MODULUS - 2);
for (int i = 0; i < n * 2; ++i) c[i] = a[i] * b[i]_;
fft(n * 2, c, -1);
for (int i = 0; i < n; ++i) c[i] = c[i] * q _;
memcpy(a, a1, n * 2 * sizeof(int64));
memcpy(b, b1, n * 2 * sizeof(int64));
}
// Calcukates f0 and f1.
void solve_1(int l, int r)
{
if (l == r) {
(f0[l] += g0[l])__;
(f1[l] += g1[l])__;
return;
}
int m = (l + r) >> 1;
solve_1(l, m);
int len = 1;
while (len < r - l + 1) len <<= 1;
for (int i = 0; i < len; ++i) q0[i] = (i + l <= m ? f0[i + l] : 0);
for (int i = 0; i < len; ++i) q1[i] = (i + l <= m ? f1[i + l] : 0);
for (int i = len; i < len * 2; ++i) q0[i] = q1[i] = 0;
convolve(len, g0, q0, t1);
convolve(len, g1, q0, t2);
convolve(len, g1, q1, t3);
convolve(len, g2, q1, t4);
for (int i = 0; i < len; ++i) {
if (i + l >= m + 1 - 1 && i + l <= r - 1) {
(f0[i + l + 1] += t1[i])__;
(f1[i + l + 1] += t2[i])__;
}
if (i + l >= m + 1 - 3 && i + l <= r - 3) {
(f0[i + l + 3] += t3[i])__;
(f1[i + l + 3] += t4[i])__;
}
}
solve_1(m + 1, r);
}
// Calculates f2.
void solve_2(int l, int r)
{
if (l == r) {
(f2[l] += (g2[l] + (l >= 1 ? t1[l - 1] : 0)))__;
return;
}
int m = (l + r) >> 1;
solve_2(l, m);
int len = 1;
while (len < r - l + 1) len <<= 1;
for (int i = 0; i < len; ++i) q0[i] = (i + l <= m ? f2[i + l] : 0);
for (int i = len; i < len * 2; ++i) q0[i] = 0;
convolve(len, g2, q0, t2);
for (int i = 0; i < len; ++i) {
if (i + l >= m + 1 - 3 && i + l <= r - 3) {
(f2[i + l + 3] += t2[i])__;
}
}
solve_2(m + 1, r);
}
int main()
{
for (int s = 0; s < LOGN; ++s)
for (int i = 0; i < (1 << s); ++i)
bitrev[s][i] = (bitrev[s][i >> 1] >> 1) | ((i & 1) << (s - 1));
for (int i = 0; i < LOGN; ++i) {
root[0][i] = qpow(PRIMITIVE, MAXN >> i);
root[1][i] = qpow(PRIMITIVE, MAXN - (MAXN >> i));
}
scanf("%d", &n);
g[0] = 1;
g[2] = 1;
for (int i = 4; i <= n; i += 2) g[i] = (g[i - 4] + g[i - 2])_;
for (int i = 0; i <= n; ++i) {
g0[i] = g[i] * i _ * i _;
g1[i] = g[i] * (i + 1)_ * (i + 1)_;
g2[i] = g[i] * (i + 2)_ * (i + 2)_;
}
solve_1(0, n);
int len = 1;
while (len < n) len <<= 1;
convolve(len, g1, f1, t1);
solve_2(0, n);
int64 ans = 0;
ans += (g[n - 1] + g[n - 3]) * (n - 1)_ * (n - 1)_ * n _;
for (int i = 2; i <= n - 2; ++i) {
ans += g0[i - 1] * f0[n - i - 1]_ * i _;
ans += g1[i - 2] * f1[n - i - 2]_ * 2 * i _;
if (i >= 3 && i <= n - 3)
ans += g2[i - 3] * f2[n - i - 3]_ * i _;
}
printf("%lld\n", ans _);
return 0;
}
|
849
|
A
|
Odds and Ends
|
Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?
Given an integer sequence $a_{1}, a_{2}, ..., a_{n}$ of length $n$. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.
A \underline{subsegment} is a contiguous slice of the whole sequence. For example, ${3, 4, 5}$ and ${1}$ are subsegments of sequence ${1, 2, 3, 4, 5, 6}$, while ${1, 2, 4}$ and ${7}$ are not.
|
What will the whole array satisfy if the answer is Yes? An odd number of segments, each having an odd length. Thus the whole array needs to have an odd length. All segments starts and ends with odd numbers, so the array begins and ends with odd numbers as well. Is that a sufficient condition? Yes, because for an array of odd length, and begins & ends with odd numbers, it's a single subsegment that satisfy the requirements itself. Thus the answer is Yes if and only if $n$ is odd, $a_{1}$ is odd, and $a_{n}$ is odd.
|
[
"implementation"
] | 1,000
|
#include <cstdio>
static const int MAXN = 102;
int n;
int a[MAXN];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
puts((n % 2 == 1) && (a[0] % 2 == 1) && (a[n - 1] % 2 == 1) ? "Yes" : "No");
return 0;
}
|
849
|
B
|
Tell Your World
|
Connect the countless points with lines, till we reach the faraway yonder.
There are $n$ points on a coordinate plane, the $i$-th of which being $(i, y_{i})$.
Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on \textbf{exactly one} of them, and each of them passes through \textbf{at least one} point in the set.
|
First way: consider the first three points. What cases are there? Denote them as $P_{1}(1, y_{1})$, $P_{2}(2, y_{2})$ and $P_{3}(3, y_{3})$. A possible Yes solution falls into one of these three cases: one of the lines pass through $P_{1}$ and $P_{2}$; passes through $P_{1}$ and $P_{3}$; or passes through $P_{2}$ and $P_{3}$. With each case, find out all the points that will be covered if the line is extended infinitely, and if there are still remaining points and all of them are collinear, then the answer is Yes. Time complexity is $O(n)$. Second way: consider the first point. A possible Yes solution falls into one of these two cases: $P_{1}$ lies alone on a line; or some $i$ exists such that one of the lines passes through $P_{1}$ and $P_{i}$. For the second case, iterate over this $i$, and do it similarly as above to check whether a possible solution exists; for the first case, either check it specially, or reverse the array and apply the check for second case again. Time complexity is $O(n^{2})$. Note that in this problem, there is no need to worry about floating point errors, since all possible slopes are either integers, or $0.5$, which can be precisely stored with IEEE doubles.
|
[
"brute force",
"geometry"
] | 1,600
|
#include <cstdio>
#include <algorithm>
static const int MAXN = 1004;
int n;
int y[MAXN];
bool on_first[MAXN];
bool check()
{
for (int i = 1; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if ((long long)i * (y[j] - y[0]) == (long long)j * (y[i] - y[0]))
on_first[j] = true;
else on_first[j] = false;
}
int start_idx = -1;
bool valid = true;
for (int j = 0; j < n; ++j) if (!on_first[j]) {
if (start_idx == -1) {
start_idx = j;
} else if ((long long)i * (y[j] - y[start_idx]) != (long long)(j - start_idx) * (y[i] - y[0])) {
valid = false; break;
}
}
if (valid && start_idx != -1) return true;
}
return false;
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &y[i]);
bool ans = false;
ans |= check();
std::reverse(y, y + n);
ans |= check();
puts(ans ? "Yes" : "No");
return 0;
}
|
850
|
A
|
Five Dimensional Points
|
You are given set of $n$ points in 5-dimensional space. The points are labeled from $1$ to $n$. No two points coincide.
We will call point $a$ bad if there are different points $b$ and $c$, not equal to $a$, from the given set such that angle between vectors $\;{\vec{a}}{\vec{b}}$ and ${\vec{a c}}$ is acute (i.e. strictly less than $90^{\circ}$). Otherwise, the point is called good.
The angle between vectors $\textstyle{\bar{x}}$ and $\overline{{y}}$ in 5-dimensional space is defined as $\mathrm{aTCCOS}\bigl(\frac{\vec{x}\cdot\vec{y}}{|\vec{x}||\vec{y}|}\bigr)$, where $\vec{x}\cdot\vec{y}=x_{1}y_{1}+x_{2}y_{2}+x_{3}y_{3}+x_{4}y_{4}+x_{5}y_{5}$ is the scalar product and $|{\vec{x}}|={\sqrt{{\vec{x}}\cdot{\vec{x}}}}$ is length of $\textstyle{\vec{x}}$.
Given the list of points, print the indices of the good points in ascending order.
|
It's easier to visualize this in 2D first. Fix a point $p$. If all other points form angles that are 90 degrees or greater, they must all be in different quadrants, so there can be at most 4 such points. In k dimension, this generalizes to 2*k such points, so for five dimensions, there can only be at most 10 other points. Thus, we can run the naive solution for small n and print 0 otherwise.
|
[
"brute force",
"geometry",
"math"
] | 1,700
| null |
850
|
B
|
Arpa and a list of numbers
|
Arpa has found a list containing $n$ numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is $1$.
Arpa can perform two types of operations:
- Choose a number and delete it with cost $x$.
- Choose a number and increase it by $1$ with cost $y$.
Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.
Help Arpa to find the minimum possible cost to make the list good.
|
Let's define $cost(g)$ the cost if we want gcd of the array becomes $g$. The answer is $min cost(g)$ for $g > 1$. Now, let's see how to calculate $cost(g)$. For each number like $c$, we can delete it with cost $x$ or we can add it till $g$ divides it. So, we must pay $\operatorname*{min}(x,y\times(\lceil{\frac{\epsilon}{g}}\rceil\times g-c))$. Let's iterate on possible values for $\lceil{\frac{c}{g}}\rceil\times g$. Before entering the main part of the solution, let's define two helper functions: - $cnt(l, r)$: this function returns the number of $i$'s such that $l \le a_{i} \le r$. - $sum(l, r)$: this function returns $\textstyle\sum_{i\geq i\leq n_{i}\leq r}a_{i}$. To implement this function, define an array $ps$, such that $ps_{i}$ keeps the sum of values less than or equal to $i$. Then $sum(l, r) = ps_{r} - ps_{l - 1}$. Now for each multiple of $g$ like $k$, let's find the cost of numbers in the range $(k - g, k]$, and sum up these values. We must find the best $f$ and divide the range into two segments $(k - g, f]$ and $(f, k]$ and delete the numbers in the first range and add the numbers in second range till they become $k$. Now to find the best value for $f$, $(g-f)\times y={\textstyle\frac{\pi}{v}}\Rightarrow f=g-\operatorname*{min}(g,{\textstyle\frac{\pi}{v}})$. So, the total cost for this range is $cnt(k - g + 1, k - \lfloor f \rfloor ) \times x + (cnt(k - \lfloor f \rfloor + 1, k) \times k - sum(k - \lfloor f \rfloor + 1, k)) \times y$. Time complexity: $O(\operatorname*{max}a_{i}\log\operatorname*{max}a_{i})$.
|
[
"implementation",
"number theory"
] | 2,100
| null |
850
|
C
|
Arpa and a game with Mojtaba
|
Mojtaba and Arpa are playing a game. They have a list of $n$ numbers in the game.
In a player's turn, he chooses a number $p^{k}$ (where $p$ is a prime number and $k$ is a positive integer) such that $p^{k}$ divides at least one number in the list. For each number in the list divisible by $p^{k}$, call it $x$, the player will delete $x$ and add $\frac{\mathcal{Z}}{p^{k}}$ to the list. The player who can not make a valid choice of $p$ and $k$ loses.
Mojtaba starts the game and the players alternatively make moves. Determine which one of players will be the winner if both players play optimally.
|
The problem is separate for each prime, so we will calculate Grundy number for each prime and xor these number to find the answer. Now let's solve the problem for some prime like $p$. Let's show the game with a $mask$, $i$-th bit of $mask$ is true if and only if there is a number in the list such that it is divisible by $p^{i}$ and it isn't divisible by $p^{k + 1}$. When some player chooses $p$ and some $k$ in his turn, in fact, he converts $mask$ to $(mask>>k)|(mask&((1<<k) - 1))$. So, for each $k$, there is an edge between state $(mask>>k)|(mask&((1<<k) - 1))$ and $mask$. We can caluclate the grundy numbers by this way.
|
[
"bitmasks",
"dp",
"games"
] | 2,200
| null |
850
|
D
|
Tournament Construction
|
Ivan is reading a book about tournaments. He knows that a tournament is an oriented graph with exactly one oriented edge between each pair of vertices. The score of a vertex is the number of edges going outside this vertex.
Yesterday Ivan learned Landau's criterion: there is tournament with scores $d_{1} ≤ d_{2} ≤ ... ≤ d_{n}$ if and only if $d_{1}+\cdot\cdot\cdot+d_{k}\geqslant{\frac{k(k-1)}{2}}$ for all $1 ≤ k < n$ and $d_{1}+d_{2}+\cdot\cdot\cdot+d_{n}={\frac{n(n-1)}{2}}$.
Now, Ivan wanna solve following problem: given a \textbf{set} of numbers $S = {a_{1}, a_{2}, ..., a_{m}}$, is there a tournament with given set of scores? I.e. is there tournament with sequence of scores $d_{1}, d_{2}, ..., d_{n}$ such that if we remove duplicates in scores, we obtain the required set ${a_{1}, a_{2}, ..., a_{m}}$?
Find a tournament with \textbf{minimum} possible number of vertices.
|
Let $n$ be the number of players participating in the tournament. First of all, note that $n \le 61$, since the total number of wins must be $\textstyle{\frac{n\times(n-1)}{2}}$, and there can be no more than $30 \times n$, therefore ${\frac{n\times(n-1)}{2}}\leq30\times n$, hence $n \le 61$. Next, we find an appropriate $n$, based on the criterion of the condition. We will go through all possible $n$ from 1 to 61 and use the dynamic programming method to determine whether there can be a given number of participants, the parameters will be: the current element in the sorted list $a_{pos}$ how many participants are already aware of their number of victories the total number of wins for the already known participants From these parameters, we store whether it is possible for the remaining participants to assign any $a_{pos}, a_{pos + 1}... a_{m}$ so that there is a tournament for these participants. Also, do not forget that each of $a_{i}$ should be taken at least once. Further, if we did not find $n$, then we print $- 1$. Otherwise, you can recover from the dynamics how many times we took each $a_{i}$, it remains to build a correct tournament on these values. To do this, each time we take the player with the smallest number of wins, let this number be $x$, and we make him win $x$ other players with the least number of wins, and loose to the remaining players. Next, delete this player, recompute for each remaining player how many times they have to win, and continue this process until all of the players are processed. The proof that a correct tournament is always built by this algorithm follows from the criterion. Thus, the first part works in $O(m^{5})$ the second part works in $O(m^{2}\times\log m)$.
|
[
"constructive algorithms",
"dp",
"graphs",
"greedy",
"math"
] | 2,800
| null |
850
|
E
|
Random Elections
|
The presidential election is coming in Bearland next year! Everybody is so excited about this!
So far, there are three candidates, Alice, Bob, and Charlie.
There are $n$ citizens in Bearland. The election result will determine the life of all citizens of Bearland for many years. Because of this great responsibility, each of $n$ citizens will choose one of six orders of preference between Alice, Bob and Charlie uniformly at random, independently from other voters.
The government of Bearland has devised a function to help determine the outcome of the election given the voters preferences. More specifically, the function is $f(x_{1},x_{2},\dots,x_{n}):\{0,1\}^{n}\rightarrow\{0,1\}$ (takes $n$ boolean numbers and returns a boolean number). The function also obeys the following property: $f(1 - x_{1}, 1 - x_{2}, ..., 1 - x_{n}) = 1 - f(x_{1}, x_{2}, ..., x_{n})$.
Three rounds will be run between each pair of candidates: Alice and Bob, Bob and Charlie, Charlie and Alice. In each round, $x_{i}$ will be equal to $1$, if $i$-th citizen prefers the first candidate to second in this round, and $0$ otherwise. After this, $y = f(x_{1}, x_{2}, ..., x_{n})$ will be calculated. If $y = 1$, the first candidate will be declared as winner in this round. If $y = 0$, the second will be the winner, respectively.
Define the probability that there is a candidate who won two rounds as $p$. $p·6^{n}$ is always an integer. Print the value of this integer modulo $10^{9} + 7 = 1 000 000 007$.
|
$b_{k}(x)$ denotes $i$-th bit of $x$. ${\mathrm{pop}}(x)$ denotes number of bits in $x$. Count number of ways where Alice wins. Suppose Alice wins in first round with mask $x$ and in third round with mask $y$ (so, $b_{i}(x) = 1$ or $b_{i}(y) = 1$ if $i$ voter preferred Alice in corresponding round). Necessary condition is $f(x) = f(y) = 1$. Assume we fixed $x$ and $y$. In how many ways we can choose orders for voters? If $b_{i}(x) = b_{i}(y)$, we can chose two valid permutations for $i$-th voter. If $b_{i}(x)\neq b_{i}(y)$, only one permutation. So, total number of permutation is $2^{n-\mathrm{pop}(x\oplus y)}$. So, answer to the problem is $\sum f(x){=}f(y){=}1\ 2^{n-}\mathrm{{pop}}(x{\vec{\omega}}y)\,.$ Denote $S = {x|f(x) = 1}$. Lets solve more general problem, for each $z$, how many pairs $(x, y)$ are there such that $z=x\oplus y$ and $x,y\in S$? This is well-known problem. There are multiple $O(2^{nn})$ solutions. Probably first usage of this problem in competitive programming can be found here https://apps.topcoder.com/wiki/display/tc/SRM+518. If you interesting in understanding this approach more deeply from math perspective, you can start investigate from here https://en.wikipedia.org/wiki/Fourier_transform_on_finite_groups. Sorry for late editorial. Btw, in task D there are always an answer (for any set S), that's called Reid's conjectue and was proven by T.X. Yao in 1988 (and have very difficult proof that I didn't manage to find in English; if somebody succeed in search, please direct it to me).
|
[
"bitmasks",
"brute force",
"divide and conquer",
"fft",
"math"
] | 2,800
| null |
850
|
F
|
Rainbow Balls
|
You have a bag of balls of $n$ different colors. You have $a_{i}$ balls of the $i$-th color.
While there are at least two different colored balls in the bag, perform the following steps:
- Take out two random balls without replacement one by one. These balls might be the same color.
- Color the second ball to the color of the first ball. You are not allowed to switch the order of the balls in this step.
- Place both balls back in the bag.
- All these actions take exactly one second.
Let $M = 10^{9} + 7$. It can be proven that the expected amount of time needed before you stop can be represented as a rational number $\frac{P}{Q}$, where $P$ and $Q$ are coprime integers and where $Q$ is not divisible by $M$. Return the value $P\cdot Q^{-1}\mod{M}$.
|
First, let's fix the final color of the balls. After fixing the final color, we can see the other colors don't matter. Define an "interesting" draw as one where we choose a ball of the final color and one of a different color. Once we do an interesting draw, we can see there is an equal probability of increasing or decreasing the number of balls of our final color. So, we can view this as a random walk, with equal probability of going in either direction. Let $X_{t}$ be the number of balls of the final color at time $t$. Let $T$ be the first time we hit 0 or $S$ balls. Now, we can write the expected value of time as follows: Let $t(r) = E(T|X_{0} = r, X_{T} = S)$ (i.e. in words, expected value of time, given we are at $r$, only counting the events that reach $X_{T} = S$ first). Let $p(r)$ be the probability of an interesting draw, so $p(r) = r \times (S - r) \times 2 / (S \times (S - 1))$. Then, we can write $t(r) = p / 2 \times t(r - 1) + p / 2 \times t(r + 1) + r / S$. Rearranging gives us $2 \times t(r) = t(r - 1) + t(r + 1) + (S - 1) / (S - r)$. So, in particular, $t(r) - t(r - 1) = t(r + 1) - t(r) + (S - 1) / (S - r)$ So, letting $g(r) = t(r) - t(r - 1)$, we get $g(r + 1) = g(r) - (S - 1) / (S - r)$. Doing some more manipulation can get us $t(r)=(S-1)\times(S-r)\sum_{i=0}^{r-1}1/(S-i)$. So, we just need to print the sum of $t(a_{i})$.
|
[
"math"
] | 2,800
| null |
851
|
A
|
Arpa and a research in Mexican wave
|
Arpa is researching the Mexican wave.
There are $n$ spectators in the stadium, labeled from $1$ to $n$. They start the Mexican wave at time $0$.
- At time $1$, the first spectator stands.
- At time $2$, the second spectator stands.
- $...$
- At time $k$, the $k$-th spectator stands.
- At time $k + 1$, the $(k + 1)$-th spectator stands and the first spectator sits.
- At time $k + 2$, the $(k + 2)$-th spectator stands and the second spectator sits.
- $...$
- At time $n$, the $n$-th spectator stands and the $(n - k)$-th spectator sits.
- At time $n + 1$, the $(n + 1 - k)$-th spectator sits.
- $...$
- At time $n + k$, the $n$-th spectator sits.
Arpa wants to know how many spectators are standing at time $t$.
|
Another solution: just print $min(t, k, n + k - t)$.
|
[
"implementation",
"math"
] | 800
| null |
851
|
B
|
Arpa and an exam about geometry
|
Arpa is taking a geometry exam. Here is the last problem of the exam.
You are given three points $a, b, c$.
Find a point and an angle such that if we rotate the page around the point by the angle, the new position of $a$ is the same as the old position of $b$, and the new position of $b$ is the same as the old position of $c$.
Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.
|
If $a, b, c$ are on the same line or $dis(a, b) \neq dis(b, c)$, the problem has not any solution.
|
[
"geometry",
"math"
] | 1,400
| null |
853
|
A
|
Planning
|
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are $n$ flights that must depart today, the $i$-th of them is planned to depart at the $i$-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first $k$ minutes of the day, so now the new departure schedule must be created.
All $n$ scheduled flights must now depart at different minutes between $(k + 1)$-th and $(k + n)$-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the $i$-th flight costs airport $c_{i}$ burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
|
We will show that following greedy is correct: let's for each moment of time use a plane, which can depart in this moment of time (and didn't depart earlier, of course) with minimal cost of delay. Proof is quite simple: it's required to minimize $\sum_{i=1}^{n}c_{i}\cdot(t_{i}-i)=\sum_{i=1}^{n}c_{i}\cdot t_{i}-\sum_{i=1}^{n}c_{i}\cdot i$. You can notice that $\textstyle\sum_{i=1}^{n}c_{i}\cdot i$ is constant, so we just need to minimize $\textstyle\sum_{i=1}^{n}c_{i}\cdot t_{i}$. Consider the optimal solution when plane $i$ departs at moment $b_{i}$ and solution by greedy algorithm in which plane $i$ departs at moment $a_{i}$. Let $x$ be plane with minimal $c_{x}$, such $a_{x} \neq b_{x}$. At any moment greedy algorithm takes avaliable plane with lowest $c_{x}$, so $a_{x} < b_{x}$. Let $y$ be a plane, such that $b_{y} = a_{x}$. But $c_{y} > = b_{y}$, so $b_{x} \cdot c_{x} + b_{y} \cdot c_{y} > = b_{x} \cdot c_{y} + b_{y} \cdot c_{x}$ and it's possible to swap $b_{x}$ and $b_{y}$ in optimal solution without loosing of optimality. By performing this operation many times it's possible to make $b_{i} = a_{i}$ for each $i$ and it means that greedy solution is optimal. To make this solution work fast you need to use some data structures to find optimal plane faster for each moment. This data structure should be able to add number into set, give value of minimal element in set and erase minimal number from set. For this purpose you can use heap (or someting like std::set or std::priority_queue in C++).
|
[
"greedy"
] | 1,500
| null |
853
|
B
|
Jury Meeting
|
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are $n + 1$ cities consecutively numbered from $0$ to $n$. City $0$ is Metropolis that is the meeting point for all jury members. For each city from $1$ to $n$ there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires $k$ days of work. For all of these $k$ days each of the $n$ jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for $k$ days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for $k$ days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than $k$ days.
|
Obviously, each member of the jury needs to buy exactly two tickets - to the capital and back. Sort all flights by the day of departure. Now go through flights to the capital (forward flights) and one by one assume it is the last forward flight in answer (let's say it is scheduled on day $d$). Thus you are assuming that all forward flights are contained in some fixed prefix of flights. Make sure that there is at least one forward flight for every jury member in this prefix and find the cheapest forward flight among them for every person. All return flights we are interested in are contained in the suffix of flights list such that every flight's departure date is at least $d + k + 1$. Take similar steps: make sure that there is at least one return flight for every jury member in this suffix and find the cheapest return flight among them for every person as well. Select minimal cost among these variants or find out that the problem has no solution. Expected complexity: $O(nm^{2})$ or $O(m^{2} + n)$. Just as the boundary of considered prefix moves right, the boundary of considered suffix moves right as well. This suggests that the problem could be solved by the two pointers method. Assume you are storing minimum forward flight's cost on current prefix (infinity if no flight exists) for every person, and you are storing multiset (ordered by cost) of all return flights on current suffix for each person as well. To proceed next prefix and conforming suffix do the following: Move prefix boundary to the next forward flight. If its cost $c_{i}$ is less than minimum forward flight's cost $fwd_{fi}$ from that city, then you could improve total cost: decrease it by $c_{i} - fwd_{fi}$ and set $fwd_{fi}$ to $c_{i}$ since it's new minimal cost. Move suffix boundary to the next backward flight until there is such flight exists and it departure date difference with prefix boundary departure date is under $k + 1$. While moving suffix boundary, keep return flights multisets consistent: remove boundary flight right before moving that boundary to the next flight. Also check out if you are removing cheapest flight from multiset. If it is so, minimal flight cost for that city changed as well as total cost: it increases by difference between old minimal cost and new minimal cost. Keep in mind that if you are removing last flight from multiset, then there is no more appropriate return flight for this city and you should terminate the process. Proceed these steps moving boundaries to the right until the process terminates. In this way you've reviewed the same prefixes and corresponding suffixes as in slower solution described above. Expected complexity: $O(m\cdot\log m+n)$.
|
[
"greedy",
"sortings",
"two pointers"
] | 1,800
| null |
853
|
C
|
Boredom
|
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.
First Ilya has drawn a grid of size $n × n$ and marked $n$ squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly $n·(n - 1) / 2$ beautiful rectangles.
Ilya has chosen $q$ query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.
Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.
|
We can't iterate over all interesting rectangles. Let's count number of rectangles that are not intersecting our rectangle. To do it let's calculate number of rectangles to the left, right, up and down of rectangle in query. It can be easily done in $O(1)$ time: suppose we have rectangle with corners $(i;p_{i})$ and $(j;p_{j})$. We have $min(i, j) - 1$ points to the left of rectangle, $n - max(i, j)$ to the right, $min(p_{i}, p_{j}) - 1$ to the down, etc. If we have $x$ points in some area, there are $\textstyle{\frac{x(x-1)}{2}}$ rectangles in that area. But now we calculated twice rectangles that are simultaneously to the left and up of our rectangle, left and down, etc. To find number of such rectangles we can iterate over all points and find points which are in these areas and find number of rectangles in area using formula $\textstyle{\frac{x(x-1)}{2}}$. The complexity is $O(q \cdot n)$. To solve the problem we need to find number of points in some areas faster. It's quite easy to notice that we just have many queries of finding number of points in some subrectangle. It's classical problem that can be solved with some 2d tree in $O(q \cdot log^{2})$ solution. But it can be too slow and can not fit into time limit in case of inaccurate implementation. However, you can notice that all queries are offline and find number of points in subrectangle in $O(q \cdot logn)$ time. It's fast enough to pass all tests.
|
[
"data structures"
] | 2,100
| null |
853
|
D
|
Michael and Charging Stations
|
Michael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs.
Michael's day starts from charging his electric car for getting to the work and back. He spends $1000$ burles on charge if he goes to the first job, and $2000$ burles if he goes to the second job.
On a charging station he uses there is a loyalty program that involves bonus cards. Bonus card may have some non-negative amount of bonus burles. Each time customer is going to buy something for the price of $x$ burles, he is allowed to pay an amount of $y$ ($0 ≤ y ≤ x$) burles that does not exceed the bonus card balance with bonus burles. In this case he pays $x - y$ burles with cash, and the balance on the bonus card is decreased by $y$ bonus burles.
If customer pays whole price with cash (i.e., $y = 0$) then 10% of price is returned back to the bonus card. This means that bonus card balance increases by $\scriptstyle{\frac{x}{10}}$ bonus burles. Initially the bonus card balance is equal to 0 bonus burles.
Michael has planned next $n$ days and he knows how much does the charge cost on each of those days. Help Michael determine the minimum amount of burles in cash he has to spend with optimal use of bonus card. Assume that Michael is able to cover any part of the price with cash in any day. It is not necessary to spend all bonus burles at the end of the given period.
|
Before solving problem one observation is required: suppose at day $i$ we have $x_{i}$ bonuses. Then exists optimal solution, which spends $0$ or $min(a_{i}, x_{i})$ bonuses every day. It's quite easy to proof: suppose we have some optimal solution and $i$ is a first day, when neither $0$ nor $min(a_{i}, x_{i})$ bonuses were spent. If $i$ is a last day on which non-zero amount of bonuses was spent, we can notice that solution spending $min(a_{i}, x_{i})$ bonuses that day is more optimal, so first solution was optimal. So let's consider next day after $i$, when non-zero amount of bonuses was spent, say $j$, and amount of bonuses spent at day $j$ is $s_{j}$ (Also, amount of bonuses spent on day $i$ is $s_{i}$). Let's look at solution that spends $s_{i} + min(s_{i} - min(a_{i}, x_{i}), s_{j})$ bonuses at day $i$ and $s_{j} - min(s_{i} - min(a_{i}, x_{i}), s_{j})$. That solution is still correct and still optimal, but it spends $min(a_{i}, x_{i})$ at day $i$ or $0$ at day $j$. Anyway this operation increases first day $i$ when neither $i$ nor $min(a_{i}, x_{i})$ bonuses were spent or first day $j$ after it, when non-zero amount of burles were spent. But we can't increase $i$ or $j$ infinitely, so, after some iterations of such transformation, solution, spending $0$ or $min(a_{i}, x_{i})$ bonuses in each day. To make an $O(n^{2})$ solution it's possible to consider dynamic programming approach: let $dp_{i, j}$ be minimum amount of money that is possible to spend at first $i$ days to pay for all chargings and have $100 \cdot j$ bonuses on card. At first, $dp_{0, 0} = 0$ and $dp_{i, j} = \infty $. Then we can easy calculate all states going through all states with something like this code: Of course, $j$ can be up to $2 \cdot n$, because at each day it's possible to earn at most 2 bonuses. To make this solution faster let's consider the following observation: there exists an optimal solution, which never has more $3000$ bonuses on bonus card. To proof it let's first proof following lemma: Lemma 1: There exists an optimal solution which spends only $0$ or $a_{i}$ bonuses at day $i$ if there are at least $3000$ bonuses at card at the beginning of day $i$. Lemma 1 proof: Let's introduce some designations. Let $x_{i}$ be amount of bonuses at the beginning of day $i$ and $s_{i}$ be amount of bonuses spent at day $i$. Also let's call day $i$ "fractional" if $s_{i} \neq 0$ and $s_{i} \neq a_{i}$, and call day $i$ "interesting" if $s_{i} \neq 0$. Let's proof lemma2 and lemma3 at first: Lemma 2: Assume $x_{i} \ge 3000$ and $j$ - next after $i$ interesting day and $k$ - next after $j$ interesting day. Then there exists an optimal solution in which $k$ is not a fractional day or $j$ is not a fractional day. Lemma2 proof: Suppose is some optimal solution $j$ and $k$ are fractional days. Let's consider a solution spending $s_{j} + min(s_{k}, a_{j} - s{j})$ bonuses at day $j$ and $s_{k} - min(s_{k}, a_{j} - s{j})$ at day $k$. This solution is still correct, because $x_{i} \ge 3000$, so for days $j$ and $k$ there is enough bonuses and still optimal. Lemma2 is proved. Lemma 3: Assume $x_{i} \ge 3000$ and $j$ - next after $i$ interesting day. Then there exists an optimal solution is which $j$ is not a fractional day. Lemma 3 proof: Consider some optimal solution with fractional day $j$. At first let's proof that $j$ is not last interesting day. Suppose, $j$ is last interesting day in solution. But we can make a solution that spends $a_{i}$ bonuses at day $i$ (because $a_{i} \le 3000$) and it will be more optimal. Contradiction. So there exists next after $j$ interesting day. Let's call it $k$. Let's consider 2 cases: Case 1 ($a_{j} = 1000$): Let's spend consider solution spending $1000$ bonuses at day $j$ and $a_{k} - (1000 - s_{j}))$ at day $k$. It's still correct and optimal but $j$ is not a fractional day. Case 2 ($a_{j} = 2000$): There are two subcases: Case 2.1 ($a_{k} = 2000$): Let's spend consider solution spending $2000$ bonuses at day $j$ and $a_{k} - (2000 - s_{j}))$ at day $k$. It's still correct and optimal but $j$ is not a fractional day. Case 2.2 ($a_{k} = 1000$): Let's proof, $k$ is not last interesting day. Assume $k$ is last interesting day. Consider a solution spending $2000$ bonuses at day $j$ and 1000 bonuses at day $k$. It's correct but more optimal that initial solution. Conrtadiction. Now let $p$ be next after $k$ interesting day ($k$ is not a fractional day by lemma2). If $2000 - a_{j} \le 1000$ we can consider solution which spends $2000$ bonuses at day $j$, $1000 - (2000 - a_{k})$ bonuses at day $k$ and $s_{p}$ bonuses at day $p$. If $2000 - s_{j} > 1000$ let's consider a solution which spends $s_{j} + 1000$ bonuses at day $j$, $0$ bonuses at day $k$ and $s_{p}$ at day $p$. But by lemma2 $s_{p} = a_{p}$, so we can consider solution that spends $2000$ bonuses at day $j$ $0$ bonuses at day $k$ and $a_{p} - (2000 - s_{j} - a_{k})$ at day $k$. All of these solutions are correct and optimal. Lemma 1 proof (end): At first, of course there is at least one interesting day after $i$ (Otherwise, it's more optimal to charge at day $i$ using bounses, but in initial solution $s_{i} = 0$ because $x_{i - 1} \le 3000$ and $x_{i} > 3000$). Let's call that day $j$ and by lemma3 $j$ is not fractional day. Let's consider 4 cases now: Case 1: ($a_{i} = 1000, a_{j} = 1000$). Let's consider a solution with $s_{i} = 1000$ and $s_{j} = 0$. It's correct and still optimal, but $x_{i} \le 3000$. Case 2: ($a_{i} = 2000, a_{j} = 2000$). Same as case1. Case 3: ($a_{i} = 2000, a_{j} = 1000$). Let's consider 2 subcases: Case 3.1: $j$ is not last interesting day. Let $k$ be next interesting day. It $a_{k} = 1000$ consider a solution spending $2000$ bonuses at day $i$, $0$ bonuses at days $j$ and $k$. It's still correct and optimal, but $x_{i} \le 3000$. If $a_{k} = 2000$ consider a solution a spending $2000$ bonuses at day $i$, $1000$ bonuses at day $j$ and $0$ bonuses at day $k$. It's correct and optimal too, and $x_{i} \le 3000$ too. Case 3.2: $j$ is last interesting day. Let's construct solution this way. At first let's set $s_{i} = 1000$ and $s_{j} = 0$. Then let's iterate over all ineteresting days after $j$, say $k$, in order in increasing time and set $s_{i} = s_{i} + min(2000 - s_{i}, s_{k}), s_{k} = s_{k} - min(2000 - s_{i}, s_{k})$. If after this process we still have some bonus left just add it to $s_{i}$. At the end, $s_{i}$ will be equal $2000$ because we spent all bonuses, solution will still be correct and optimal, but $x_{i} \le 3000$. Case 4: ($a_{i} = 1000, a_{j} = 2000$). Let $p$ be last day before $i$ with $s_{p} \neq 0$. If $a_{p} = 1000$ consider a solution with $s_{p} = 0, s_{i} = 0, s_{j} = 2000$. It's correct, optimal and $x_{t} \le 3000$ for each $t \le i$. If $a_{p} = 2000$, consider a solution with $s_{p} = 2000, s_{i} = 0, s_{j} = 0$. It's correct, optimal and $x_{t} \le 3000$ for each $t \le i$, too. So for all cases we can make correct and optimal solution such there is no $x_{i} \le 3000$ for all $i$, or number of first day with $x_{i} > 3000$ increases, but it can't increase forever, so after some amount of opereations solution with $x_{i} \le 3000$ for all $i$ will be constructed. Because of this fact we can consider dynamic programming approach described before but notice, that we should consider only states with $j \le 30$. It will have $O(n)$ complexity. Moreover, looking at states with $j = 30$ is required. It's possible to make a test on which solution, that looks at states with $j \le 29$ will be incorrect.
|
[
"binary search",
"dp",
"greedy"
] | 2,400
| null |
853
|
E
|
Lada Malina
|
After long-term research and lots of experiments leading Megapolian automobile manufacturer «AutoVoz» released a brand new car model named «Lada Malina». One of the most impressive features of «Lada Malina» is its highly efficient environment-friendly engines.
Consider car as a point in $Oxy$ plane. Car is equipped with $k$ engines numbered from $1$ to $k$. Each engine is defined by its velocity vector whose coordinates are $(vx_{i}, vy_{i})$ measured in distance units per day. An engine may be turned on at any level $w_{i}$, that is a real number between $ - 1$ and $ + 1$ (inclusive) that result in a term of $(w_{i}·vx_{i}, w_{i}·vy_{i})$ in the final car velocity. Namely, the final car velocity is equal to
\[
(w_{1}·vx_{1} + w_{2}·vx_{2} + ... + w_{k}·vx_{k}, w_{1}·vy_{1} + w_{2}·vy_{2} + ... + w_{k}·vy_{k})
\]
Formally, if car moves with constant values of $w_{i}$ during the whole day then its $x$-coordinate will change by the first component of an expression above, and its $y$-coordinate will change by the second component of an expression above. For example, if all $w_{i}$ are equal to zero, the car won't move, and if all $w_{i}$ are equal to zero except $w_{1} = 1$, then car will move with the velocity of the first engine.
There are $n$ factories in Megapolia, $i$-th of them is located in $(fx_{i}, fy_{i})$. On the $i$-th factory there are $a_{i}$ cars «Lada Malina» that are ready for operation.
As an attempt to increase sales of a new car, «AutoVoz» is going to hold an international exposition of cars. There are $q$ options of exposition location and time, in the $i$-th of them exposition will happen in a point with coordinates $(px_{i}, py_{i})$ in $t_{i}$ days.
Of course, at the «AutoVoz» is going to bring as much new cars from factories as possible to the place of exposition. Cars are going to be moved by enabling their engines on some certain levels, such that at the beginning of an exposition car gets exactly to the exposition location.
However, for some of the options it may be impossible to bring cars from some of the factories to the exposition location by the moment of an exposition. Your task is to determine for each of the options of exposition location and time how many cars will be able to get there by the beginning of an exposition.
|
In the original contest there were subtasks for this problem and it's more convinient to understand the editorial going through these subtasks, so we will leave them here. The key part of a solution is to understand what are the locations that may be accessed from the origin in $T$ seconds. First observation is that we should investigate it only in case when $T = 1$ because $T$ is simply a scale factor. Let's denote this set for $T = 1$ as $P$. Group #1. For the first group it's easy to see that P is a square with vertices in points $( \pm 2, 0), (0, \pm 2)$. So, the first group may be solved with a straightforward $O(qn)$ approach: we iterate through all the factories and check if it's possible to get for cars from $i$-th factories to the car exposition. We can rotate the plane by $45$ degrees (this may be done by the transformation $x' = x + y, y' = x - y$), after this each query region looks like a square. Therefore, it's necessary to check if point lies inside a square: $\begin{array}{c}{{\left\{-2T\le(p x_{i}-f x_{j})+(p y_{i}-f y_{j})\le2T}}\\ {{\left(-2T\le(p x_{i}-f x_{j})-(p y_{i}-f y_{j})\le2T}}\end{array}\right.$ Group #2. In the second group propeller velocities are two arbitrary vectors. It can be shown that $P$ will always be a parallelogram centered in the origin, built on vectors $2v_{1}$ and $2v_{2}$ as sides. Thus, this group is a matter of the same $O(qn)$ approach with a bit more complicated predicate: one should be able to check that an integer point belongs to an integer parallelogram. The key observation is that we may find an appropriate transformation of a plane that transforms this set into a rectangle. Indeed, there always exists an affine transformation performing what we want. As an additional requirement, we want to transform coordinates in such way that they are still integral and not much larger than the original coordinates. The transformation looks like following: $\\,{\,\binom{x^{\prime}=v x_{1}\cdot y-v y_{1}\cdot x}{y^{\prime}=v x_{2}\cdot y-v y_{2}\cdot x}}$ The first expression is a signed distance to the line parallel to the vector $v_{1}$, and the second one is the signed distance from the line parallel to the vector $v_{2}$. Easy to see that belonging to some query parallelogram can be formulated in terms of $x'$ and $y'$ independendly belonging to some ranges. Group #3. Second group should be a hint for the third group. One can find that the set $P = {w_{1v}_{1} + ... + w_{kv}_{k}||w_{i}| \le 1}$ is always a central-symmetric polygon with the center in the origin. Actually, this Polygon is a Minkowski sum of $k$ segments $[ - v_{i}, v_{i}]$. Minkowski sum of sets $A_{1}, A_{2}, ..., A_{k}$ is by definition the following set: $A_{1}+A_{2}+\ldots+A_{k}=\{a_{1}+a_{2}+\ldots+a_{k}|a_{1}\in A_{1},a_{2}\in A_{2},\ldots,a_{k}\in A_{k}\}$. It can be built in $O(k\log k)$ time, although in this problem $k$ is very small, so one may use any inefficient approach that comes into his head, like building a convex hull of all points ${ \pm v_{1} \pm v_{2}... \pm v_{k}}$. After we found out a form of $P$, it's possible to solve the third group of tests in $O(qnk)$ by checking if each possible factory location belongs into a query polygon in $O(k)$ time. Following groups are exactly the same, but the constraints are higher, they require using some geometric data structure to deal with range queries. Groups #4 and #5. Fourth group and fifth group are very similar to first and second group correspondingly, but we need to process the requests faster. After the transformation of the plane, the request can be reformulated as "find sum of all factories inside a square", so any 2d data structure may be applied, like a segment tree of segment trees. Another approach is to use a sweeping line algorithm with a segment tree or an appropriate binary search tree, achieving a time complexity $O((q+n)\log^{2}n)$ or $O((q+n)\log n)$. Group #6. To solve the sixth group we need to use a trapezoidal polygon area calculation algorithm applied to our problem. Calculate the sum of points in each of $2k$ trapezoid areas below each of the sides of a polygon, and then take them with appropriate signs to achieve a result. Such trapezoid area can be seen as a set of points satisfying the inequalities $l \le x \le r$ and $y \le kx + b$. Under transformation $x' = x, y' = y - kx$, this area becomes a rectangle, leading us to an $O((q+n)k\log n)$ time solution.
|
[
"data structures",
"geometry"
] | 3,400
| null |
854
|
A
|
Fraction
|
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction $\frac{a}{b}$ is called proper iff its numerator is smaller than its denominator ($a < b$) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except $1$).
During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button ($ + $) instead of division button ($÷$) and got sum of numerator and denominator that was equal to $n$ instead of the expected decimal notation.
Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction $\frac{a}{b}$ such that sum of its numerator and denominator equals $n$. Help Petya deal with this problem.
|
It's possible to look over all possible values of the numerator $1\leqslant a\leqslant\lfloor{\frac{n}{2}}\rfloor$. For the current value of $a$ we have to compute denominator as $b = n - a$, check that there are no common divisors (except $1$) of $a$ and $b$ (it also could be done by a linear search of possible common divisors $2 \le d \le a$). The answer is the maximal fraction that was considered during the iteration over all possible values of the numerator and passed the irreducibility test. Pseudocode of the described solution is presented below: This solution have $O(n^{2})\,$ time complexity. However, we can find answer to the problem analytically in the following way:
|
[
"brute force",
"constructive algorithms",
"math"
] | 800
| null |
854
|
B
|
Maxim Buys an Apartment
|
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has $n$ apartments that are numbered from $1$ to $n$ and are arranged in a row. Two apartments are adjacent if their indices differ by $1$. Some of the apartments can already be inhabited, others are available for sale.
Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly $k$ already inhabited apartments, but he doesn't know their indices yet.
Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.
|
Minimum number of good apartments is almost always $1$, since rooms with indices from $1$ to $k$ could be inhabited. Exceptions are cases in which $k = 0$ and $k = n$, in these cases both minimum and maximum number of good rooms is $0$ since there is no inhabitant or vacant apartments. Maximum number of good apartments could be reached, for example, as follows. Assume apartments with indices $2$, $5$, $8$ and so on are occupied as much as possible. Each of these apartments produces $2$ good rooms except from, if it exists, the one with index $n$ (that apartment produces $1$ good apartment). If number of inhabitant apartments is less than $k$ occupy any of rest rooms to reach that number, every such occupation will decrease number of good apartments by one). Simulate this process, than count the number of good rooms to find maximum possible number. Expected complexity: $O(n^{2})$ or $O(n)$. Instead of simulating the above process calculate number of apartments with indices $2$, $5$, $8$ and so on excluding the one with index $n$ if it exists. Number of that apartments is equal to $x=\lfloor{\frac{n}{3}}\rfloor$, and if $k \le x$ you can occupy some of these apartments to reach maximum number of good rooms equal to $2 \cdot k$. Otherwise, if $k > x$, assume that apartments with indices $2$, $5$, $8$ and so on are occupied, so any room has at least one inhabited room adjacent to it. Therefore number of good apartments is equal to number of vacant apartments and is equal to $n - k$. Implementation of these formulas with keeping in mind cases in which $k = 0$ and $k = n$ will be scored as full solution of problem. Expected complexity: $O(1)$.
|
[
"constructive algorithms",
"math"
] | 1,200
| null |
855
|
A
|
Tom Riddle's Diary
|
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of $n$ people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name $s_{i}$ in the $i$-th line, output "YES" (without quotes) if there exists an index $j$ such that $s_{i} = s_{j}$ and $j < i$, otherwise, output "NO" (without quotes).
|
For each string $s_{i}$ iterate $j$ from $1$ to $i - 1$. Check if $s_{i} = s_{j}$ for any value of $j$. If it is output "YES", otherwise output "NO". Output will always be "NO" for the first string. The expected complexity was $O(n^{2}\cdot\operatorname*{max}_{1\leq i\leq n}(|s_{i}|))$
|
[
"brute force",
"implementation",
"strings"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define ll long long
#define mod 1000000007
#define bitcount __builtin_popcountll
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define pi pair<int,int>
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n,i,j;
string s[102];
sd(n);
for(i=0;i<n;i++)
{
cin>>s[i];
for(j=0;j<i;j++)
{
if(s[i]==s[j])
break;
}
if(j==i)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}
|
855
|
B
|
Marvolo Gaunt's Ring
|
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly $x$ drops of the potion he made.
Value of $x$ is calculated as maximum of $p·a_{i} + q·a_{j} + r·a_{k}$ for given $p, q, r$ and array $a_{1}, a_{2}, ... a_{n}$ such that $1 ≤ i ≤ j ≤ k ≤ n$. Help Snape find the value of $x$. Do note that the value of $x$ may be negative.
|
There can be two approaches: First solution : Create a dynamic programming table of size $n \cdot 3$. In this, $dp[i][0]$ stores maximum of value $p \cdot a_{x}$ for $x$ between $1$ and $i$. Similarly $dp[i][1]$ stores the maximum value of $p \cdot a_{x} + q \cdot a_{y}$ such that $x \le y \le i$ and $dp[i][2]$ stores maximum value of $p \cdot a_{x} + q \cdot a_{y} + r \cdot a_{z}$ for $x \le y \le z \le i$. To calculate the dp: $dp[i][0] = max(dp[i - 1][0], p \cdot a_{i})$ $dp[i][1] = max(dp[i - 1][1], dp[i][0] + q \cdot a_{i})$ $dp[i][2] = max(dp[i - 1][2], dp[i][1] + r \cdot a_{i})$ The answer will be stored in $dp[n][2]$ Second Solution : Maintain $4$ arrays, storing maximum and minimum from left, maximum and minimum from right. Let us call them $minLeft, minRight, maxLeft$ and $maxRight$. Then iterate $j$ through the array. Calculate $sum = q \cdot a_{j}$. Now, if $p < 0$, add $minLeft_{i} \cdot p$ to $sum$. Otherwise add $maxLeft_{i} \cdot p$ to $sum$. Similarly, if $r > 0$, add $maxRight_{i} \cdot r$, otherwise add $minRight_{i} \cdot r$ to $sum$. Expected time complexity: $O(n)$
|
[
"brute force",
"data structures",
"dp"
] | 1,500
|
#include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define mod 1000000007
#define bitcount __builtin_popcountll
#define ll long long
#define pb push_back
#define pi pair<int,int>
#define pii pair<pi,int>
#define mp make_pair
int minleft[100005],minright[100005],maxleft[100005],maxright[100005],a[100005];
int main()
{
int i,j,k;
int n,p,q,r;
cin>>n>>p>>q>>r;
for(i=1;i<=n;i++)
sd(a[i]);
minleft[1]=maxleft[1]=a[1];
minright[n]=maxright[n]=a[n];
for(i=2;i<=n;i++)
{
minleft[i]=min(minleft[i-1],a[i]);
maxleft[i]=max(maxleft[i-1],a[i]);
}
for(i=n-1;i>=1;i--)
{
minright[i]=min(minright[i+1],a[i]);
maxright[i]=max(maxright[i+1],a[i]);
}
ll ans=-3e18;
for(i=1;i<=n;i++)
{
ll leftval = (p<0) ? 1ll*minleft[i]*p : 1ll*maxleft[i]*p;
ll rightval = (r<0) ? 1ll*minright[i]*r : 1ll*maxright[i]*r;
ans=max(ans,leftval+rightval+1ll*q*a[i]);
}
cout<<ans<<endl;
return 0;
}
|
855
|
C
|
Helga Hufflepuff's Cup
|
Harry, Ron and Hermione have figured out that Helga Hufflepuff's cup is a horcrux. Through her encounter with Bellatrix Lestrange, Hermione came to know that the cup is present in Bellatrix's family vault in Gringott's Wizarding Bank.
The Wizarding bank is in the form of a tree with total $n$ vaults where each vault has some type, denoted by a number between $1$ to $m$. A tree is an undirected connected graph with no cycles.
The vaults with the highest security are of type $k$, and all vaults of type $k$ have the highest security.
\textbf{There can be at most $x$ vaults of highest security}.
Also, \textbf{if a vault is of the highest security, its adjacent vaults are guaranteed to not be of the highest security and their type is guaranteed to be less than $k$}.
Harry wants to consider every possibility so that he can easily find the best path to reach Bellatrix's vault. So, you have to tell him, given the tree structure of Gringotts, the number of possible ways of giving each vault a type such that the above conditions hold.
|
This problem can be solved by using the concept of dp on trees. The dp table for this problem will be of the size $n \cdot 3 \cdot x$. We can assume any one node as the root and apply dfs while computing the dp array. Let the root be $1$. Here, $dp[curr][0][cnt]$ represent the number of ways of assigning type to each node in the subtree of $curr$ such that number of nodes with value $k$ in this subtree is $cnt$ and type at $curr$ is less than $k$. $dp[curr][1][cnt]$ represent the number of ways of assigning type to each node in the subtree of $curr$ such that number of nodes with value $k$ in this subtree is $cnt$ and type at $curr$ is equal to $k$. $dp[curr][2][cnt]$ represent the number of ways of assigning type to each node in the subtree of $curr$ such that number of nodes with value $k$ in this subtree is $cnt$ and type at $curr$ is greater than $k$. Now, to compute this dp for a node, curr, we assume this dp array is computed for its children. Then, we can combine them two nodes at a time to form the dp array for the node curr. While assigning the value to $dp[curr][1][cnt]$, we take into account only the values of $dp[childofcurr][0][cnt - z]$. Similarly for $dp[curr][2][cnt]$, we take into account only $dp[child of curr][0][cnt - z]$ and $dp[child of curr][2][cnt - z]$. For combining the value we make $x * x$ computations. Final answer will be $\textstyle\sum_{0\leq i\leq2}\sum_{0\leq j\leq x}d p[1][i][j]$ The expected time complexity of the solution is: $O(n \cdot 3 \cdot x \cdot x)$
|
[
"dp",
"trees"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define ll long long
#define mod 1000000007
#define bitcount __builtin_popcountll
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define pi pair<int,int>
int dp[100005][3][12],x,k,m;
int a[3][12],b[3][12];
vector <int> q[100005];
void dfs(int cur,int par)
{
int i,j=0,l,r,temp;
for(i=0;i<q[cur].size();i++)
{
if(q[cur][i]==par)
continue;
j=1;
dfs(q[cur][i],cur);
}
if(!j)
{
dp[cur][0][0]=k-1;
dp[cur][1][1]=1;
dp[cur][2][0]=m-k;
return;
}
for(i=0;i<3;i++)
{
for(j=0;j<=x;j++)
{
a[i][j]=0;
b[i][j]=0;
}
}
for(i=0;i<3;i++)
a[i][0]=1;
for(i=0;i<q[cur].size();i++)
{
if(q[cur][i]==par)
continue;
for(j=0;j<3;j++)
{
for(l=0;l<=x;l++)
{
for(r=0;r<=x;r++)
{
if(l+r>x)
continue;
if(j==0)
{
temp=dp[q[cur][i]][0][r]+dp[q[cur][i]][1][r];
if(temp>=mod)
temp-=mod;
temp+=dp[q[cur][i]][2][r];
if(temp>=mod)
temp-=mod;
b[j][l+r]+=(1ll*a[j][l]*temp)%mod;
if(b[j][l+r]>=mod)
b[j][l+r]-=mod;
}
else if(j==1)
{
b[j][l+r]+=(1ll*a[j][l]*(dp[q[cur][i]][0][r]))%mod;
if(b[j][l+r]>=mod)
b[j][l+r]-=mod;
}
else
{
temp=dp[q[cur][i]][0][r]+dp[q[cur][i]][2][r];
if(temp>=mod)
temp-=mod;
b[j][l+r]+=(1ll*a[j][l]*temp)%mod;
if(b[j][l+r]>=mod)
b[j][l+r]-=mod;
}
}
}
}
for(j=0;j<3;j++)
{
for(l=0;l<=x;l++)
{
a[j][l]=b[j][l];
b[j][l]=0;
}
}
}
for(l=0;l<=x;l++)
{
dp[cur][0][l]=(1ll*a[0][l]*(k-1))%mod;
if(l>=1)
dp[cur][1][l]=a[1][l-1];
dp[cur][2][l]=(1ll*a[2][l]*(m-k))%mod;
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n,i,j,ans;
sd(n);
sd(m);
for(i=1;i<n;i++)
{
sd(j);
sd(k);
q[j].pb(k);
q[k].pb(j);
}
sd(k);
sd(x);
dfs(1,0);
ans=0;
for(i=0;i<3;i++)
{
for(j=0;j<=x;j++)
{
//printf("%d %d %d\n",i,j,dp[1][i][j]);
ans+=dp[1][i][j];
if(ans>=mod)
ans-=mod;
}
}
printf("%d\n",ans);
return 0;
}
|
855
|
D
|
Rowena Ravenclaw's Diadem
|
Harry, upon inquiring Helena Ravenclaw's ghost, came to know that she told Tom Riddle or You-know-who about Rowena Ravenclaw's diadem and that he stole it from her.
Harry thought that Riddle would have assumed that he was the only one to discover the Room of Requirement and thus, would have hidden it there. So Harry is trying to get inside the Room of Requirement to destroy the diadem as he knows that it is a horcrux.
But he has to answer a puzzle in order to enter the room. He is given $n$ objects, numbered from $1$ to $n$. Some of the objects have a parent object, that has a lesser number. Formally, object $i$ may have a parent object $parent_{i}$ such that $parent_{i} < i$.
There is also a type associated with each parent relation, it can be either of type $1$ or type $2$. Type $1$ relation means that the child object is like a special case of the parent object. Type $2$ relation means that the second object is \textbf{always} a part of the first object and all its special cases.
Note that if an object $b$ is a special case of object $a$, and $c$ is a special case of object $b$, then $c$ is considered to be a special case of object $a$ as well. The same holds for parts: if object $b$ is a part of $a$, and object $c$ is a part of $b$, then we say that object $c$ is a part of $a$. Also note, that if object $b$ is a part of $a$, and object $c$ is a special case of $a$, then $b$ is a part of $c$ as well.
An object is considered to be neither a part of itself nor a special case of itself.
Now, Harry has to answer two type of queries:
- 1 u v: he needs to tell if object $v$ is a special case of object $u$.
- 2 u v: he needs to tell if object $v$ is a part of object $u$.
|
In this problem, the relations "is a part of" and "is a special case of" were transitive. And also, if some object "a" had "b" as its special case and "c" as its part, "c" was also a part of "b". Now, when we need to process the queries, we use the concept of lowest common ancestor (lca). For query $1 u v$, answer will be "YES" iff $u \neq v$ (as u is not special case of itself) and $lca(u, v) = u$ and all the relations from $u$ to $v$ are of type $0$ (is a special case of) For query $2 u v$, answer will be "YES" iff the following conditions hold: If $w = lca(u, v)$, path from $w$ to $u$ has only edges of type $0$ (is a special case of) and those from $w$ to $v$ has only edges of type $1$ (is a part of). Also, $w \neq v$. Expected time complexity: $O((n + q) \cdot log(n))$
|
[
"trees"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define mod 1000000007
#define bitcount __builtin_popcountll
#define ll long long
#define pb push_back
#define pi pair<int,int>
#define pii pair<pi,int>
#define mp make_pair
vector<int>v[100005],v2[100005];
int inherit[100005],comp[100005],parent[100005][25],height[100005];
int parr[100005];
int findpar(int node)
{
return parr[node]==node ? node : parr[node]=findpar(parr[node]);
}
void dfs(int node, int par, int inh, int com)
{
parent[node][0]=par;
inherit[node]=inh;
comp[node]=com;
height[node]=height[par]+1;
for(int i=1;i<=20;i++)
{
parent[node][i]=parent[parent[node][i-1]][i-1];
}
for(int i=0;i<v[node].size();i++)
{
if(v[node][i]==par)
continue;
if(v2[node][i]==0)
dfs(v[node][i],node,inh+1,com);
else
dfs(v[node][i],node,inh,com+1);
}
}
int findlca(int u, int v)
{
if(height[u]>height[v])
swap(u,v);
for(int i=20;i>=0;i--)
{
if(height[parent[v][i]]>=height[u])
{
v=parent[v][i];
}
}
if(u!=v)
{
for(int i=20;i>=0;i--)
{
if(parent[u][i]!=parent[v][i])
{
u=parent[u][i];
v=parent[v][i];
}
}
u=parent[u][0];
v=parent[v][0];
}
return u;
}
int main()
{
int i,j,k;
int n,q;
sd(n);
for(i=1;i<=n;i++)
parr[i]=i;
for(i=1;i<=n;i++)
{
sd(j);
sd(k);
if(j==-1 && k==-1)
continue;
v[i].pb(j);
v[j].pb(i);
v2[i].pb(k);
v2[j].pb(k);
int x=findpar(i);
int y=findpar(j);
if(x!=y)
parr[x]=y;
}
for(i=1;i<=n;i++)
{
if(parent[i][0]==0)
{
dfs(i,i,0,0);
}
}
sd(q);
while(q--)
{
sd(i);
sd(j);
sd(k);
int x=findpar(j);
int y=findpar(k);
if(x!=y)
{
printf("NO\n");
continue;
}
x=findlca(j,k);
if(i==1)
{
if(x!=j || comp[k]-comp[x]!=0 || j==k)
{
printf("NO\n");
}
else
printf("YES\n");
}
else
{
if(inherit[k]-inherit[x]!=0 || comp[j]-comp[x]!=0 || x==k)
printf("NO\n");
else
printf("YES\n");
}
}
return 0;
}
|
855
|
E
|
Salazar Slytherin's Locket
|
Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher.
Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers $l$ and $r$ (both inclusive).
Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base $b$, all the digits from $0$ to $b - 1$ appear even number of times in its representation without any leading zeros.
You have to answer $q$ queries to unlock the office. Each query has three integers $b_{i}$, $l_{i}$ and $r_{i}$, the base and the range for which you have to find the count of magic numbers.
|
This problem can be solved using precomputation of dp table $dp[base][mask][len]$. This stores the number of integers in base $b$ and length $len$ that forms the given $mask$ in their representation. The $mask$ is defined as having $i - th$ bit as $1$, if the digit $i - 1$ occurs odd number of times in the representation. Using this precomputed $dp$ array, we can easily calculate the answer for the queries, by converting $l - 1$ and $r$ to the given base $b$, then adding the total integers less than equal to $r$ with $mask = 0$ and subtracting those less than $l$ with $mask = 0$. Now, to find the number of integers less than equal to $l - 1$ with $mask = 0$, we first add all the integers with $mask = 0$ who have length less than length of $l - 1$ in base $b$ representation. If length of $l - 1$ in base $b$ is $l_{b}$, this value can be calculated as $\textstyle\sum_{1<i<l a}d p[b][b](i)-d p[b][1][i-1]$. The second term is subtracted to take into account the trailing zeros. Now, we need to calculate the number of integers with length$= l_{b}$ and value$ \le l - 1$ and $mask = 0$. Let the number $l - 1$ in base $b$ representation be $l_{0}, l_{1}... l_{lb}$. Then, if we fix the first digit of our answer, $x$ from $0$ to $l_{0} - 1$, we can simply calculate the mask for remaining digits we need as $2^{x}$ and thus adding $dp[b][2^{x}][len - 1]$ to answer. Now, if we fix the first digit as $l_{0}$ only, we can simply perform the same operation for the second digit, selecting value of second digit, $y$ from $0$ to $l_{1} - 1$, and thus adding $d p[b](l e n-2][2^{x}\oplus2^{y}]$ to answer. And, we can move forward to rest of the digits in the same way. The overall complexity of the solution will be $O(b\cdot2^{b}\cdot\log_{b}10^{18}+q\cdot b\cdot\log_{b}r)$
|
[
"bitmasks",
"dp"
] | 2,200
|
#include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%lld",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define ll long long
#define mod 1000000007
#define bitcount __builtin_popcountll
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define pi pair<int,int>
ll dp[11][2][1030][70];
ll len[12],a[100];
ll f(ll b,ll in,ll m,ll pos)
{
if(dp[b][in][m][pos]!=-1)
return dp[b][in][m][pos];
if(pos==0)
{
if(in!=0&&m==0)
return dp[b][in][m][pos]=1;
else
return dp[b][in][m][pos]=0;
return dp[b][in][m][pos];
}
ll j=0;
if(in==0)
j+=f(b,0,m,pos-1);
else
j+=f(b,1,(m^1),pos-1);
for(ll i=1;i<b;i++)
j+=f(b,1,(m^(1<<i)),pos-1);
dp[b][in][m][pos]=j;
return j;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
ll n,i,j,k,in;
ll ans,l,r,m,q,b;
k=1e18;
memset(dp,-1,sizeof dp);
for(i=2;i<=10;i++)
{
len[i]=1;
j=i;
while(j<k)
{
len[i]++;
j*=i;
}
f(i,0,0,len[i]+1);
}
sd(q);
while(q--)
{
sd(b);
sd(l);
sd(r);
ans=0;
l--;
if(l)
{
j=l;
i=0;
while(j)
{
a[i]=j%b;
j/=b;
i++;
}
m=0;
in=0;
for(j=i-1;j>=0;j--)
{
for(k=0;k<a[j];k++)
{
if(k!=0)
in=1;
if(in==0)
ans-=dp[b][0][m][j];
else
ans-=dp[b][1][(m^(1<<k))][j];
}
if(in|a[j])
{
in=1;
m=(m^(1<<a[j]));
}
}
ans-=dp[b][in][m][0];
}
j=r;
i=0;
while(j)
{
a[i]=j%b;
j/=b;
i++;
}
in=0;
m=0;
for(j=i-1;j>=0;j--)
{
for(k=0;k<a[j];k++)
{
if(k!=0)
in=1;
if(in==0)
ans+=dp[b][0][m][j];
else
ans+=dp[b][1][(m^(1<<k))][j];
}
if(in|a[j])
{
in=1;
m=(m^(1<<a[j]));
}
}
ans+=dp[b][in][m][0];
printf("%lld\n",ans);
}
return 0;
}
|
855
|
F
|
Nagini
|
Nagini, being a horcrux You-know-who created with the murder of Bertha Jorkins, has accumulated its army of snakes and is launching an attack on Hogwarts school.
Hogwarts' entrance can be imagined as a straight line (x-axis) from $1$ to $10^{5}$. Nagini is launching various snakes at the Hogwarts entrance. Each snake lands parallel to the entrance, covering a segment at a distance $k$ from $x = l$ to $x = r$. Formally, each snake can be imagined as being a line segment between points $(l, k)$ and $(r, k)$. Note that $k$ can be both positive and negative, but not $0$.
Let, at some $x$-coordinate $x = i$, there be snakes at point $(i, y_{1})$ and point $(i, y_{2})$, such that $y_{1} > 0$ and $y_{2} < 0$. Then, if for any point $(i, y_{3})$ containing a snake such that $y_{3} > 0$, $y_{1} ≤ y_{3}$ holds and for any point $(i, y_{4})$ containing a snake such that $y_{4} < 0$, $|y_{2}| ≤ |y_{4}|$ holds, then the danger value at coordinate $x = i$ is $y_{1} + |y_{2}|$. If no such $y_{1}$ and $y_{2}$ exist, danger value is $0$.
Harry wants to calculate the danger value of various segments of the Hogwarts entrance. Danger value for a segment $[l, r)$ of the entrance can be calculated by taking the sum of danger values for each integer $x$-coordinate present in the segment.
Formally, you have to implement two types of queries:
- 1 l r k: a snake is added parallel to entrance from $x = l$ to $x = r$ at y-coordinate $y = k$ ($l$ inclusive, $r$ exclusive).
- 2 l r: you have to calculate the danger value of segment $l$ to $r$ ($l$ inclusive, $r$ exclusive).
|
This problem can be solved by using the concept of square root decomposition. Let us divide the total range of x-axis, that is, from $1$ to $10^{5}$ in $\sqrt{10^{5}}$. Then, blockSize = $\sqrt{10^{5}}$, and number of blocks, $n_{b}$ = $10^{5} / blockSize$. Now, we maintain the following structures: An array $ans$ that stores the answer for each block. Two values $upper$ and $lower$ for each block. $upper$ stores the closest line segment with $y > 0$ that covers the complete block. Similarly $lower$ stores the closest line with $y < 0$ that covers the complete block. Maps $low$ and $up$ for each block. $up$ maps for each height $y > 0$, the number of x-coordinates with its minimum height as $y$. Similarly $low$ maps for each height $y < 0$, the number of x-coordinates with its maximum height as $y$. Also, note that this map stores the information only for those x-coordinates which have atleast one line segment on both sides of axis. Maps $vnotup$ and $vnotdown$ for each block. These are similar to maps $low$ and $up$ except that these stores value for those coordinates that do not have line on one of the sides. That is, $vnotup$ maps the height $y$ to its count for $y < 0$ such that at those coordinates, there do not exists any line for $y > 0$. Value $notboth$ for each block, this stores the number of x-coordinates that do not have line segments on any of the two sides of axis. Arrays $minup$ and $mindown$ for each value from $1$ to $10^{5}$. $minup$ stores the minimum value for $y$ such that $y > 0$ and there is a snake at that point and that snake does not cover the complete block. Similar value for $y < 0$ is stored by $mindown$ Now we have to maintain these structure throughout the update operation. To do so, we divide the update operations into two halves, the update for initial and final blocks which are only partially covered by a line, and the update for complete block. For now, let us assume that the update is for some $y > 0$. For $y < 0$, a similar approach can be done: Updating the initial and final blocks: Iterate through every x-coordinate in the range. There can be four cases: If all the values, $minup$, $mindown$ for that coordinate and value $lower$ and $upper$ for that block are inf, this means that this is the first time a line is coming at this coordinate. Reduce $notboth$ of the block by $1$ and update the map $vnotdown$. Else if $minup$ and $upper$ are inf, this means that for this x-coordinate there is a line below axis, but not above. Update $vnotup$, $up$, $low$ and $ans$ accordingly. Else if $mindown$ and $lower$ are inf, this means that there is no line with $y < 0$ at this x-coordinate. Just update $vnotdown$. Else if both side lines are there, just update $ans$ and $up$. Also, update the value of $minup$ for each coordinate. Updating the complete block Remove all the elements from $vnotup$ and update the $up$, $low$ maps and $ans$ for that block accordingly. Put $notboth$ as $0$ and update the map $vnotdown$ acccordingly. Remove elements from $vnotdown$ which are greater than this value of $y$ and update it again. Finally update the $up$ array and value of $ans$ for that block. Also update the value of $upper$. For answering the queries, you will need to answer the half-block(initial and final block) queries by iterating through each x-coordinate. For answering full-block queries, just return the $ans$ for that block. If we take $n = 10^{5}$, the expected complexity of the solution is $O(q\cdot{\sqrt{n}}\cdot\log n)$
|
[
"binary search",
"data structures"
] | 3,100
|
#include<bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define slld(x) scanf("%lld",&x)
#define ss(x) scanf("%s",x)
#define mod 1000000007
#define bitcount __builtin_popcountll
#define ll long long
#define pb push_back
#define fi first
#define se second
#define pi pair<int,int>
#define pii pair<pi,int>
#define mp make_pair
ll ans[1000];
int upper[1000],lower[1000];
int block;
map <int,int> low[1000],up[1000];
map <int,int> vnotup[1000],vnotdown[1000];
int notboth[1000];
int minup[100005],mindown[100005];
void updateup(int i,int l,int r,int val)
{
if(upper[i]<=val)
return;
//map<int,int> m;
map<int,int> :: iterator it;
//m.clear();
for(int j=l;j<=r;j++)
{
if(minup[j]>val)
{
if(minup[j]==mod&&mindown[j]==mod&&upper[i]==mod&&lower[i]==mod)
{
notboth[i]--;
//notdown[i]++;
vnotdown[i][val]++;
//notdownsum[i]+=val;
}
else if(minup[j]==mod&&upper[i]==mod)
{
//notup[i]--;
int temp=min(lower[i],mindown[j]);
vnotup[i][temp]--;
if(vnotup[i][temp]==0)
vnotup[i].erase(temp);
//notupsum[i]-=min(lower[i],mindown[j]);
up[i][val]++;
low[i][temp]++;
ans[i]+=val;
ans[i]+=min(lower[i],mindown[j]);
}
else if(mindown[j]==mod&&lower[i]==mod)
{
int temp=min(upper[i],minup[j]);
vnotdown[i][temp]--;
if(vnotdown[i][temp]==0)
vnotdown[i].erase(temp);
vnotdown[i][val]++;
}
else
{
ans[i]+=val-min(upper[i],minup[j]);
up[i][min(minup[j],upper[i])]--;
up[i][val]++;
}
minup[j]=val;
}
}
}
void updatefullup(int i,int val)
{
if(val>=upper[i])
return;
map <int,int> :: iterator it;
int n=up[i].size();
n--;
ll sum=0;
int len2=0;
for(it=vnotup[i].begin();it!=vnotup[i].end();it++)
{
ans[i]+=1ll*(it->fi)*(it->se)+1ll*(it->se)*val;
len2+=it->se;
low[i][it->fi]+=it->se;
}
vnotup[i].clear();
it=vnotdown[i].upper_bound(val);
int temp=0;
for(it;it!=vnotdown[i].end();it++)
{
temp+=it->se;
}
it=vnotdown[i].upper_bound(val);
vnotdown[i].erase(it,vnotdown[i].end());
vnotdown[i][val]+=temp+notboth[i];
notboth[i]=0;
int len=0;
it=up[i].upper_bound(val);
for(it;it!=up[i].end();it++)
{
sum+=1ll*(it->fi)*(it->se);
len+=it->se;
}
it=up[i].upper_bound(val);
up[i].erase(it,up[i].end());
ans[i]+=1ll*len*val-sum;
up[i][val]+=len+len2;
upper[i]=val;
}
void updatedown(int i,int l,int r,int val)
{
if(lower[i]<=val)
return;
//map<int,int> m;
map<int,int> :: iterator it;
//m.clear();
for(int j=l;j<=r;j++)
{
if(mindown[j]>val)
{
if(mindown[j]==mod&&minup[j]==mod&&upper[i]==mod&&lower[i]==mod)
{
notboth[i]--;
//notup[i]++;
//notupsum[i]+=val;
vnotup[i][val]++;
}
else if(mindown[j]==mod&&lower[i]==mod)
{
//notdown[i]--;
int temp=min(upper[i],minup[j]);
vnotdown[i][temp]--;
if(vnotdown[i][temp]==0)
vnotdown[i].erase(temp);
low[i][val]++;
up[i][temp]++;
//notdownsum[i]-=min(upper[i],minup[j]);
ans[i]+=val;
ans[i]+=min(upper[i],minup[j]);
}
else if(minup[j]==mod&&upper[i]==mod)
{
int temp=min(lower[i],mindown[j]);
vnotup[i][temp]--;
if(vnotup[i][temp]==0)
vnotup[i].erase(temp);
vnotup[i][val]++;
}
else
{
ans[i]+=val-min(lower[i],mindown[j]);
low[i][min(mindown[j],lower[i])]--;
low[i][val]++;
}
mindown[j]=val;
}
}
}
void updatefulldown(int i,int val)
{
if(val>=lower[i])
return;
map <int,int> :: iterator it;
int n=low[i].size();
n--;
ll sum=0;
int len2=0;
for(it=vnotdown[i].begin();it!=vnotdown[i].end();it++)
{
ans[i]+=1ll*(it->fi)*(it->se)+1ll*(it->se)*val;
len2+=it->se;
up[i][it->fi]+=it->se;
}
vnotdown[i].clear();
it=vnotup[i].upper_bound(val);
int temp=0;
for(it;it!=vnotup[i].end();it++)
{
temp+=it->se;
}
it=vnotup[i].upper_bound(val);
vnotup[i].erase(it,vnotup[i].end());
vnotup[i][val]+=temp+notboth[i];
notboth[i]=0;
int len=0;
it=low[i].upper_bound(val);
for(it;it!=low[i].end();it++)
{
sum+=1ll*(it->fi)*(it->se);
len+=it->se;
}
it=low[i].upper_bound(val);
low[i].erase(it,low[i].end());
ans[i]+=1ll*len*val-sum;
low[i][val]+=len+len2;
lower[i]=val;
}
ll query(int i,int l,int r)
{
ll sum=0;
for(int j=l;j<=r;j++)
{
if(min(upper[i],minup[j])<mod&&min(lower[i],mindown[j])<mod)
sum+=min(upper[i],minup[j])+min(lower[i],mindown[j]);
}
return sum;
}
ll queryfull(int i)
{
return ans[i];
}
int main()
{
int i,j,k,q,n,t,l,r,val,block;
ll s;
n=100000;
for(i=0;i<1000;i++)
lower[i]=upper[i]=mod;
for(i=0;i<=100000;i++)
minup[i]=mindown[i]=mod;
block=300;
for(i=1;i<=n;i++)
{
j=i/block;
notboth[j]++;
}
sd(q);
while(q--)
{
sd(t);
sd(l);
sd(r);
r--;
if(t==1)
{
sd(val);
i=l/block;
j=r/block;
if(val>0)
{
if(i==j)
updateup(j,l,r,val);
else
{
updateup(i,l,(i+1)*block-1,val);
i++;
while(i<j)
{
// updateup(i,i*block,(i+1)*block-1,val);
updatefullup(i,val);
i++;
}
updateup(j,j*block,r,val);
}
}
else
{
if(i==j)
updatedown(j,l,r,-val);
else
{
updatedown(i,l,(i+1)*block-1,-val);
i++;
while(i<j)
{
// updatedown(i,i*block,(i+1)*block-1,-val);
updatefulldown(i,-val);
i++;
}
updatedown(j,j*block,r,-val);
}
}
}
else
{
s=0;
i=l/block;
j=r/block;
if(i==j)
s=query(j,l,r);
else
{
s=query(i,l,(i+1)*block-1);
i++;
while(i<j)
{
//s+=query(i,i*block,(i+1)*block-1);
s+=queryfull(i);
i++;
}
s+=query(j,j*block,r);
}
printf("%lld\n",s);
}
}
return 0;
}
|
855
|
G
|
Harry Vs Voldemort
|
After destroying all of Voldemort's Horcruxes, Harry and Voldemort are up for the final battle. They each cast spells from their wands and the spells collide.
The battle scene is Hogwarts, which can be represented in the form of a tree. There are, in total, $n$ places in Hogwarts joined using $n - 1$ undirected roads.
Ron, who was viewing this battle between Harry and Voldemort, wondered how many triplets of places $(u, v, w)$ are there such that if Harry is standing at place $u$ and Voldemort is standing at place $v$, their spells collide at a place $w$. This is possible for a triplet only when $u$, $v$ and $w$ are distinct, and there exist paths from $u$ to $w$ and from $v$ to $w$ which do not pass through the same roads.
Now, due to the battle havoc, new paths are being added all the time. You have to tell Ron the answer after each addition.
Formally, you are given a tree with $n$ vertices and $n - 1$ edges. $q$ new edges are being added between the nodes of the tree. After each addition you need to tell the number of triplets $(u, v, w)$ such that $u$, $v$ and $w$ are distinct and there exist two paths, one between $u$ and $w$, another between $v$ and $w$ such that these paths do not have an edge in common.
|
At first let's solve the problem for the initial tree. You can use dynamic programming. The second part of the problem was to realize that we need to count the triple $(u, v, w)$ if and only if the following condition holds: $w$ is in a edge-2-connectivity component that is on the path from the edge-2-connectivity component of $u$ and the edge-2-connectivity of $v$. When an edge is added, it compresses all edge-2-connectivity components on the path between its ends. We can list all these components and then merge them in $O(number of the components)$ time, because once we list all these components, they disappear. In other words, each component is listed at most once through the entire process, and the total number of components is $O(n)$. How do we recalculate the answer given the components we need to merge into a single one? It can be done directly considering all cases of which of $u$, $v$ and $w$ are in this new component. The only tough idea may be that you need to, for each component, keep the number of pairs $(u, v)$ such that $u$ and $v$ are not in this component, and edges (bridges) towards $u$ and $v$ from this component are different. For more details about case-work see the code below.
|
[
"dfs and similar",
"dp",
"graphs",
"trees"
] | 3,300
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
#ifdef WIN32
#define LLD "%I64d"
#else
#define LLD "%lld"
#endif
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
const int maxn = 200005;
struct tpath
{
int rep, sz;
ll ansmiddle;
int edgeleft, edgeright;
};
int p[maxn], s[maxn];
int sz[maxn], down[maxn], up[maxn], top[maxn];
vector<tpath> path, path2;
vector<int> gr[maxn];
ll dp1[maxn], dp2[maxn], ansmiddle[maxn];
int n, m;
ll answer;
int tin[maxn], tout[maxn];
int timer;
inline int find(int a)
{
return (a == p[a] ? a : p[a] = find(p[a]));
}
inline bool isparent(int a, int b)
{
return tin[a] <= tin[b] && tout[a] >= tin[b];
}
void unite(int a, int b)
{
a = find(a);
b = find(b);
if (a == b) return;
if (s[a] > s[b]) swap(a, b);
p[a] = b;
if (s[a] == s[b]) s[b]++;
if (tin[top[a]] < tin[top[b]])
{
sz[top[a]] += sz[top[b]];
top[b] = top[a];
} else
{
sz[top[b]] += sz[top[a]];
}
}
void findpath(int a, int b)
{
a = top[find(a)];
b = top[find(b)];
// cout << "findpath " << a << ' ' << b << endl;
int lastdowna = 0;
while (!isparent(a, b))
{
path.pb({a, sz[a], ansmiddle[a], lastdowna, n - down[a]});
lastdowna = down[a];
a = top[find(up[a])];
}
path2.clear();
int lastdownb = 0;
while (a != b)
{
path2.pb({b, sz[b], ansmiddle[b], n - down[b], lastdownb});
lastdownb = down[b];
b = top[find(up[b])];
}
path.pb({a, sz[a], ansmiddle[a], lastdowna, lastdownb});
reverse(all(path2));
for (auto t : path2) path.pb(t);
}
void addedge(int a, int b)
{
if (find(a) == find(b)) return;
path.clear();
findpath(a, b);
// cout << "addedge " << a << ' ' << b << endl;
// for (auto t : path) cout << "(" << t.rep << ' ' << t.sz << ' ' << t.ansmiddle << ' ' << t.edgeleft << ' ' << t.edgeright << ")" << endl;
// 3
ll cnt0 = 1;
ll cnt1 = 0;
ll cnt2 = 0;
for (auto t : path)
{
answer -= t.sz * cnt2 * 2 + (ll)t.sz * (t.sz - 1) * cnt1 * 2 + (ll)t.sz * (t.sz - 1) * (t.sz - 2);
cnt2 += t.sz * cnt1 + (ll)t.sz * (t.sz - 1) * cnt0;
cnt1 += t.sz * cnt0;
}
ll sum = cnt1;
answer += ((ll)sum * (sum - 1) * (sum - 2));
// cout << "after 3: " << answer << endl;
// 2
cnt1 = 0;
for (auto t : path)
{
answer += cnt1 * (t.edgeleft - cnt1) * t.sz * 2;
cnt1 += t.sz;
}
cnt1 = 0;
for (int i = (int)path.size() - 1; i >= 0; i--)
{
auto &t = path[i];
answer += cnt1 * (t.edgeright - cnt1) * t.sz * 2;
cnt1 += t.sz;
}
// cout << "after 2: " << answer << endl;
// 1
cnt1 = 0;
cnt2 = 0;
for (auto t : path)
{
answer += cnt2 * t.sz * 2;
cnt2 += (n - t.edgeright - t.edgeleft - t.sz) * cnt1;
cnt1 += n - t.edgeright - t.edgeleft - t.sz;
}
cnt1 = 0;
cnt2 = 0;
for (int i = (int)path.size() - 1; i >= 0; i--)
{
auto &t = path[i];
answer += cnt2 * t.sz * 2;
cnt2 += (n - t.edgeleft - t.edgeright - t.sz) * cnt1;
cnt1 += n - t.edgeleft - t.edgeright - t.sz;
}
// cout << "after 1 old: " << answer << endl;
ll ttldown1 = 0;
ll ttldown2 = 0;
for (auto t : path)
{
ll curdown = n - t.edgeleft - t.edgeright - t.sz;
ll curdown2 = t.ansmiddle - curdown * (t.edgeleft + t.edgeright) * 2 - (ll)t.edgeleft * t.edgeright * 2;
answer += curdown2 * (sum - t.sz);
ttldown2 = ttldown2 + curdown2 + ttldown1 * curdown * 2;
ttldown1 += curdown;
}
// cout << "after 1: " << answer << endl;
for (int i = 1; i < (int)path.size(); i++) unite(path[i - 1].rep, path[i].rep);
ansmiddle[top[find(path[0].rep)]] = ttldown2;
}
int go(int cur, int pr)
{
down[cur] = 1;
up[cur] = pr;
dp1[cur] = 0;
ansmiddle[cur] = 0;
tin[cur] = timer++;
for (auto t : gr[cur]) if (t != pr)
{
down[cur] += go(t, cur);
answer += (ll)dp1[t] * dp1[cur] * 2;
answer += (ll)dp1[t] * dp2[cur] * 2 + dp2[t] * dp1[cur] * 2;
ansmiddle[cur] += (ll)dp1[t] * dp1[cur] * 2;
answer += dp2[t] * 2;
dp2[cur] += dp2[t];
dp1[cur] += dp1[t];
}
ansmiddle[cur] += (ll)(n - down[cur]) * dp1[cur] * 2;
dp2[cur] += dp1[cur];
dp1[cur] += 1;
tout[cur] = timer - 1;
// cout << "exit " << cur << ' ' << answer << ' ' << dp1[cur] << ' ' << dp2[cur] << endl;
return down[cur];
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n - 1; i++)
{
int a, b;
scanf("%d%d", &a, &b);
a--, b--;
gr[a].pb(b);
gr[b].pb(a);
}
go(0, -1);
for (int i = 0; i < n; i++)
{
p[i] = i;
s[i] = 0;
top[i] = i;
sz[i] = 1;
}
printf("%lld\n", answer);
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
int a, b;
scanf("%d%d", &a, &b);
a--, b--;
addedge(a, b);
printf("%lld\n", answer);
}
return 0;
}
|
856
|
A
|
Set Theory
|
Masha and Grisha like studying sets of positive integers.
One day Grisha has written a set $A$ containing $n$ different integers $a_{i}$ on a blackboard. Now he asks Masha to create a set $B$ containing $n$ different integers $b_{j}$ such that all $n^{2}$ integers that can be obtained by summing up $a_{i}$ and $b_{j}$ for all possible pairs of $i$ and $j$ are different.
Both Masha and Grisha don't like big numbers, so all numbers in $A$ are from $1$ to $10^{6}$, and all numbers in $B$ must also be in the same range.
Help Masha to create the set $B$ that satisfies Grisha's requirement.
|
First let us prove that the answer is always YES. Let us iterate over $b_{j}$ and check if summing it up with all $a_{i}$ values don't result in values that we already have. If no conflict is found, add the corresponding $b_{j}$ to $B$. Let us give some estimate for the maximum element of $B$. The reason that we cannot include $b_{j2}$, to $B$ is the equality $a_{i1} + b_{j1} = a_{i2} + b_{j2}$, so $b_{j2} = b_{j1} - (a_{i2} - a_{i1})$. Each element of $B$ forbids $O(n^{2})$ values, so $max(B)$ is $O(n^{3})$. That means that the answer always exists for the given constraints. Now let us speed up the test that we can add a number to $B$. Let us use an array $bad$, that marks the numbers that we are not able to include to $B$. When trying the value $b_{j}$, we can add it to $B$ if it is not marked in $bad$. Now the numbers that are equal to $b_{j} + a_{i1} - a_{i2}$ are forbidden, let us mark them in $bad$. The complexity is $O(n^{3})$ for each test case.
|
[
"brute force",
"constructive algorithms"
] | 1,600
| null |
856
|
B
|
Similar Words
|
Let us call a non-empty sequence of lowercase English letters a \underline{word}. \underline{Prefix} of a word $x$ is a word $y$ that can be obtained from $x$ by removing zero or more last letters of $x$.
Let us call two words \underline{similar}, if one of them can be obtained from the other by removing its first letter.
You are given a set $S$ of words. Find the maximal possible size of set of non-empty words $X$ such that they satisfy the following:
- each word of $X$ is prefix of some word from $S$;
- $X$ has no similar words.
|
Let us consider the following similarity graph: the vertices are the prefixes of the given words, two vertices are connected by an edge if the corresponding words are similar. Note that the set of vertices in this graph is the same as in the trie for the given words, so it doesn't exceed the sum of lengths of words. Let us prove that the resulting graph is a forest. If two words are similar, let us call the shorter one the parent of the longer one. Each vertex now has at most one parent, and there are no cycles, so the graph is a set of trees - a forest. Now the required set is the independent set in the constructed similarity graph, so we can use dynamic programming or greedy algorithm to find it. There are two ways to construct the similarity graph. Way 1. Hashes For each prefix find its hash, make a set of all hashes. Now for each prefix remove its first letter, check if such hash exists. If it does, connect them by an edge. Way 2. Aho-Corasick Let us build Aho-Corasick automaton for the given set of words. The vertices of the similarity graph are automaton vertices. An edge exists between two vertices if the suffix link from one of them goes to the other one, and their depths differ by exacly $1$.
|
[
"dp",
"hashing",
"strings",
"trees"
] | 2,300
| null |
856
|
C
|
Eleventh Birthday
|
It is Borya's eleventh birthday, and he has got a great present: $n$ cards with numbers. The $i$-th card has the number $a_{i}$ written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers $1$, $31$, and $12$, and he puts them in a row in this order, he would get a number $13112$.
He is only 11, but he already knows that there are $n!$ ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because $13112 = 1192 × 11$, but if he puts the cards in the following order: $31$, $1$, $12$, he would get a number $31112$, it is not divisible by $11$, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.
Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.
Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo $998244353$.
|
Let us use divisibility rule for eleven. The number is divisible by eleven if the sum of digits at odd positions is equal to the sum of digits at even positions modulo 11. So for each number on a card there are only two parameters that we care about: the sign interchanging sum of its digits with digits at odd positions positive and digits at even position negative, and the parity of its digit count. Let us divide all cards to two groups: with even digit count and with odd digit count. Let us first put cards with numbers that have odd count of digits. Half of them (rounded up) will have their sign interchanging sum used as positive, other half as negative. Let us use dynamic programming to find the number of ways to sum them up to have a given sum modulo 11. The state includes the number of cards considered, the number of cards that are used as positive, and the current sum modulo 11. There are two transitions: take the current card as positive, and take it as negative. If there are no cards with odd digit count, no matter how you order even digit count cards the result modulo 11 is the same. So the answer is either $0$ or $n!$. In the other case each even digit count card can be used either as positive, or as negative, independent of the other cards. Use analogous dynamic programming to count the number of ways to get each possible sum modulo 11. Finally, combine results for even and odd digit count cards, getting the total sum modulo 11 equal to 0. Time complexity is $O(n^{2})$.
|
[
"combinatorics",
"dp",
"math"
] | 2,400
| null |
856
|
D
|
Masha and Cactus
|
Masha is fond of cacti. When she was a little girl, she decided to plant a tree. Now Masha wants to make a nice cactus out of her tree.
Recall that \underline{tree} is a connected undirected graph that has no cycles. \underline{Cactus} is a connected undirected graph such that each vertex belongs to at most one cycle.
Masha has some additional edges that she can add to a tree. For each edge she knows which vertices it would connect and the \underline{beauty} of this edge. Masha can add some of these edges to the graph if the resulting graph is a cactus. \underline{Beauty} of the resulting cactus is sum of beauties of all added edges.
Help Masha find out what maximum \underline{beauty} of the resulting cactus she can achieve.
|
Let us use dynamic programming for a rooted tree and some data structures. Denote as $f_{v}$ the maximal total beauty of edges that have both ends in a subtree of $v$, such that if we add them all to the subtree it would be a cactus. To calculate $f_{v}$ let us consider two cases: $v$ belongs to some cycle, or it doesn't. If it doesn't belong to any cycle, $f_{v}$ is equal to the sum of $f_{u}$ for all children $u$ of $v$. If $v$ belongs to a cycle, let us iterate over all possible cycles it can belong to. Such cycle is generated by an added edge $(x, y)$ such that $LCA(x, y) = v$. Try all possible such edges and then temporarily delete a path from $x$ to $y$ from a tree, calculate the sum of $f_{u}$ for all $u$ - roots of the isolated subtrees after the deletion of the path, and add it to the beauty of $(x, y)$. Now we have an $O(nm)$ solution. To speed up this solution let us use some data structures. First, we need to calculate $LCA$ for all endpoints of the given edges, any fast enough standard algorithm is fine. The second thing to do is to be able to calculate the sum of $f_{u}$ for all subtrees after removing the path. To do it, use the following additional values: $g_{u} = f_{p} - f_{u}$, where $p$ is the parent of $u$, and $s_{v} = sum(f_{u})$, where $u$ are the children of $v$. Now the sum of $f_{u}$ for all subtrees after $x - y$ path removal is the sum of the following values: $s_{x}$, $s_{y}$, $s_{v} - f_{x'} - f_{y'}$, the sum of $g_{i}$ for all $i$ at $[x, x')$, the sum of $g_{i}$ for all $i$ at $[y, y')$, where $x'$ is the child of $v$ that has $x$ in its subtree, and $y'$ is the child of $v$ that has $y$ in its subtree. We need some data structure for a tree that supports value change in a vertex and the sum for a path, range tree or Fenwick are fine. The complexity is $O((n + m)log(n))$.
|
[
"dp",
"trees"
] | 2,400
| null |
856
|
E
|
Satellites
|
Real Cosmic Communications is the largest telecommunication company on a far far away planet, located at the very edge of the universe. RCC launches communication satellites.
The planet is at the very edge of the universe, so its form is half of a circle. Its radius is $r$, the ends of its diameter are points $A$ and $B$. The line $AB$ is the edge of the universe, so one of the half-planes contains nothing, neither the planet, nor RCC satellites, nor anything else. Let us introduce coordinates in the following way: the origin is at the center of $AB$ segment, $OX$ axis coincides with line $AB$, the planet is completely in $y > 0$ half-plane.
The satellite can be in any point of the universe, except the planet points. Satellites are never located beyond the edge of the universe, nor on the edge itself — that is, they have coordinate $y > 0$. Satellite antennas are directed in such way that they cover the angle with the vertex in the satellite, and edges directed to points $A$ and $B$. Let us call this area the satellite \underline{coverage area}.
The picture below shows coordinate system and coverage area of a satellite.
When RCC was founded there were no satellites around the planet. Since then there have been several events of one of the following types:
- 1 x y — launch the new satellite and put it to the point $(x, y)$. Satellites never move and stay at the point they were launched. Let us assign the number $i$ to the $i$-th satellite in order of launching, starting from one.
- 2 i — remove satellite number $i$.
- 3 i j — make an attempt to create a communication channel between satellites $i$ and $j$. To create a communication channel a repeater is required. It must not be located inside the planet, but can be located at its half-circle border, or above it. Repeater must be in coverage area of both satellites $i$ and $j$. To avoid signal interference, it must not be located in coverage area of any other satellite. Of course, the repeater must be within the universe, it must have a coordinate $y > 0$.
For each attempt to create a communication channel you must find out whether it is possible.
Sample test has the following satellites locations:
|
Any point $X$ can be given by two angles $ \alpha = XAB$ and $ \beta = XBA$. The point $( \alpha _{2}, \beta _{2})$ is in coverage area of a satellite at the point $( \alpha _{1}, \beta _{1})$, if $ \alpha _{2} \le \alpha _{1}$ and $ \beta _{2} \le \beta _{1}$. Let two satellites that want to create a communication channel are at points $( \alpha _{1}, \beta _{1})$ and $( \alpha _{2}, \beta _{2})$. Repeater must be positioned in such point $( \alpha _{0}, \beta _{0})$, that $ \alpha _{0} \le min( \alpha _{1}, \alpha _{2})$ and $ \beta _{0} \le min( \beta _{1}, \beta _{2})$. To make it harder for it to get to other satellites coverage area, it is reasonable to maximize $ \alpha _{0}$ and $ \beta _{0}$: $ \alpha _{0} = min( \alpha _{1}, \alpha _{2})$, $ \beta _{0} = min( \beta _{1}, \beta _{2})$. Now let us move to a solution. Consider a query of type $3$: you are given two satellites at points $( \alpha _{1}, \beta _{1})$ and $( \alpha _{2}, \beta _{2})$. You must check whether the point $( \alpha _{0}, \beta _{0}) = (min( \alpha _{1}, \alpha _{2}), min( \beta _{1}, \beta _{2}))$ is not in the coverage area of any other satellite. That means that among all satellites with $ \alpha \ge \alpha _{0}$ the maximum value of $ \beta $ is smaller than $ \beta _{0}$. The solution is offline, it considers all satellites from the test data and just turns them on and off. Sort all satellites by $ \alpha $. Each moment for each satellite we store its $ \beta $ if it exists, or $- \infty $ if it doesn't. Let us build a range tree for maximum, and update values as satellites come and go. The query is a range maximum. To avoid considering the satellites from the query, change their values to $- \infty $ before the query, and restore them afterwards. The next thing to do is to get rid of floating point numbers. Instead of calculating the angle values, we will only compare them using cross product. Similarly, instead of storing $ \beta $ values in range tree, we will store indices and compare them by cross product in integers. The final remark: we need to check that the point $( \alpha _{0}, \beta _{0})$ is not inside the planet. The point is inside the planet, if the angle $AXB$ is obtuse, that can be checked by a scalar product of $XA$ and $XB$. The point $X$ can have non-integer coordinates, so we will not look for it, but will use colinear vectors from among those connecting satellite points to $A$ and $B$.
|
[] | 3,100
| null |
856
|
F
|
To Play or not to Play
|
Vasya and Petya are playing an online game. As most online games, it has hero progress system that allows players to gain experience that make their heroes stronger. Of course, Vasya would like to get as many experience points as possible. After careful study of experience points allocation, he found out that if he plays the game alone, he gets one experience point each second. However, if two players are playing together, and their current experience values differ by at most $C$ points, they can boost their progress, and each of them gets 2 experience points each second.
Since Vasya and Petya are middle school students, their parents don't allow them to play all the day around. Each of the friends has his own schedule: Vasya can only play during intervals $[a_{1};b_{1}], [a_{2};b_{2}], ..., [a_{n};b_{n}]$, and Petya can only play during intervals $[c_{1};d_{1}], [c_{2};d_{2}], ..., [c_{m};d_{m}]$. All time periods are given in seconds from the current moment. Vasya is good in math, so he has noticed that sometimes it can be profitable not to play alone, because experience difference could become too big, and progress would not be boosted even when played together.
Now they would like to create such schedule of playing that Vasya's final experience was greatest possible. The current players experience is the same. Petya is not so concerned about his experience, so he is ready to cooperate and play when needed to maximize Vasya's experience.
|
Let us introduce coordinates $y(x)$, where $x = exp_{1} - exp_{2}$, and $y = exp_{1}$ ($exp_{1}$, $exp_{2}$ - experience of the first and the second player, respectively). Let us proceed with time, and keep the set of possible states at this plane. It is a polygon. Lemma 1: in the optimal solution if at some moment both players can play the game simultaneously, they should do so. Now consider all moments of time, one after another. There are three transitions that modify the polygon: The first player can play for $t$ seconds. The new polygon is the Minkowski sum of the previous polygon and the degenerate polygon: segment with two vertices $(0, 0)$ and $(t, t)$. The second player can play for $t$ seconds. The new polygon is the Minkowski sum of the previous polygon and the segment with vertices $(0, 0)$ and $( - t, 0)$. Both players can play for $t$ seconds. Now all points with $x$-coordinates $[ - C;C]$ have $2t$ added to their $y$ coordinate, and other points have $t$ added to their $y$ coordinate. Let us now see how the polygon looks like. It is $x$-monotonous polygon (each line parallel to $y$-axis intersects it via a segment), the lower bound of this polygon is $y = 0$ if $x \le 0$ and $y = x$ if $x > 0$. Let us see how the upper bound of the polygon looks like. We want to prove that $y$-coordinate of the upper bound of the polygon doesn't decrease, and it only contains segments that move by vectors $( + 1, 0)$ and $( + 1, + 1)$. We attempt an induction, and the induction step is fine for the first two transitions. But the third transition can make the upper bound non-monotonous at a point $x = C$. To fix it, let us change the definition of our polygon. Instead of storing all possible reachable points, we will keep larger set, that contains the original set, and for each of its point we can get maximal experience for the first player not greater than what we could originally get. Lemma 2: if at some moment $t$ we take two points $P_{1} = (x_{1}, y_{1})$ and $P_{2} = (x_{2}, y_{2})$ such that $C \le x_{1} \le x_{2}$, and $y_{1} \ge y_{2}$, and our player start training from those states, the maximal experience for point $P_{2}$ is not greater than for the point $P_{1}$. So we can expand our upper bound for $x$ from $[C; + inf)$ by a maximum value of the correct upper bound and $y = y(C)$. The similar proof works for a line $y = y(C) - (C - x)$ for $x$ in $( - inf;C]$. Now we have an upper bound as a polyline that contains $( + 1, 0)$ and $( + 1, + 1)$ segments. All is left to do is to modify the polyline using the described transitions. This can be done using some appropriate data structure, treap for example. The solution works in $O(nlog(n))$.
|
[
"greedy"
] | 3,000
| null |
858
|
A
|
k-rounding
|
For a given positive integer $n$ denote its $k$-rounding as the minimum positive integer $x$, such that $x$ ends with $k$ or more zeros in base $10$ and is divisible by $n$.
For example, $4$-rounding of $375$ is $375·80 = 30000$. $30000$ is the minimum integer such that it ends with $4$ or more zeros and is divisible by $375$.
Write a program that will perform the $k$-rounding of $n$.
|
Notice that the number $x$ ends with $k$ or more zeros if the maximal power of $2$ that is a divisor of $x$ is at least $k$ and the maximal power of $5$ that is a divisor of $x$ is at least $k$. Let's calculate the maximal powers of $2$ and $5$ that are divisors of $n$. If any of the powers is less than $k$ then multiply the number by appropriate number of $2$ and $5$. The answer is also $LCM(n, 10^{k})$.
|
[
"brute force",
"math",
"number theory"
] | 1,100
| null |
858
|
B
|
Which floor?
|
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from $1$ from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from $1$.
Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.
Given this information, is it possible to restore the exact floor for flat $n$?
|
We will store our current answer in some variable $ans$. Initially it is -1. Let's iterate over the quantity of the flats on each floor (it will be from 1 to 100 inclusive). Let it be $cf$. Then we have to check that this quantity coincides with given input. If $\textstyle\left[{\frac{k_{i}}{c f}}\right]\neq f_{i}$ for any $i\in[1..m]$ then this quantity is incorrect. Now if $a n s\neq-1\ \ \&8\times\vert\frac{n}{c f}\vert\neq a n s$ then we can't determine on which floor flat $n$ is situated. Print -1. In the other case set $\begin{array}{r c l}{{a n s}}&{{=}}&{{\left|{\frac{n}{c f}}\right|}}\end{array}$.
|
[
"brute force",
"implementation"
] | 1,500
| null |
858
|
C
|
Did you mean...
|
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.
For example:
- the following words have typos: "hellno", "hackcerrs" and "backtothefutttture";
- the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo".
When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.
Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.
|
We will solve the problem greedily. Let's find the leftmost typo. It will be three consecutive characters $s_{i - 1}, s_{i}$ and $s_{i + 1}$ such that all of them are consonants and there are at least two diffirent letters. It is clear that we can cut this string after position $i$, because prefix will be correct and we will leave only one letter in the remaining part of the string. So each time we find the leftmost typo and cut out the prefix. Remember that after cutting the prefix you have to continue checking from index $i + 2$, not $i + 1$.
|
[
"dp",
"greedy",
"implementation"
] | 1,500
| null |
858
|
D
|
Polycarp's phone book
|
There are $n$ phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from $0$. All the numbers are distinct.
There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: $123456789$, $100000000$ and $100123456$, then:
- if he enters $00$ two numbers will show up: $100000000$ and $100123456$,
- if he enters $123$ two numbers will show up $123456789$ and $100123456$,
- if he enters $01$ there will be only one number $100123456$.
For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
|
Find the shortest substring of each string such that it doesn't appear in any other string as a substring. For each substring let's store the index of the string which contains this substring or $- 1$ if there are more than one such string. Iterate over all substrings which have values that are not $- 1$ and update the answer for the corresponding string.
|
[
"data structures",
"implementation",
"sortings"
] | 1,600
| null |
858
|
E
|
Tests Renumeration
|
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.
Vladimir wants to rename the files with tests so that their names are distinct integers starting from $1$ without any gaps, namely, "1", "2", ..., "$n$', where $n$ is the total number of tests.
Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.
The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command.
Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run:
- all examples are the first several tests having filenames "1", "2", ..., "$e$", where $e$ is the total number of examples;
- all other files contain regular tests with filenames "$e + 1$", "$e + 2$", ..., "$n$", where $n$ is the total number of all tests.
|
Firstly we will get rid of all tests that are already named correctly. After this, let's call samples "tests of 1 type", and system tests "tests of 2 type". Let's denote "free positions" such indices $i\ (i\in[1..n])$ such that there is currently no test with the name $i$. If there are no any free positions, then we can't rename each test using only one operation $move$ because firstly we have to make its index a free position. Let's show that one free position is always enough. If there is one, then let's put some test of the corresponding type which has wrong name (a name that doesn't coincide with its type) into this position. It is clear that there will be at least one such test - otherwise all tests of corresponding type are at their positions, and there is no free position of this type. Then there are two cases - either we free a correct position (then we will have another free position) or we move a test which had illegal name (so we don't create any free positions). It's better to move a test which occupies some position so we will have a new free position after it. It is clear that when there are no tests such that their names are correct numbers, but they are in position of different type, then we can't keep the quantity of free positions as it is, and after moving any test this quantity will decrease. This approach is optimal because we will have to perform either $cnt$ ($cnt$ is the number of tests that aren't correctly named initially) or $cnt + 1$ operations. $cnt + 1$ will be the answer only if we have to make an operation that will create a free position (if there are no free positions initially). This number of operations is optimal because if we have $cnt$ incorrectly named tests, then we can't rename them in less than $cnt$ operations; and this is possible only if we have at least one free position initially; otherwise we have to free some position.
|
[
"greedy",
"implementation"
] | 2,200
| null |
858
|
F
|
Wizard's Tour
|
All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland!
It is well-known that there are $n$ cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that the road network is connected, i.e. it is possible that you can't reach some city from some other.
The tour will contain several episodes. In each of the episodes:
- the wizard will disembark at some city $x$ from the Helicopter;
- he will give a performance and show a movie for free at the city $x$;
- he will drive to some neighboring city $y$ using a road;
- he will give a performance and show a movie for free at the city $y$;
- he will drive to some neighboring to $y$ city $z$;
- he will give a performance and show a movie for free at the city $z$;
- he will embark the Helicopter and fly away from the city $z$.
It is known that the wizard doesn't like to use roads, so he agrees to use each road at most once (regardless of direction). In other words, for road between $a$ and $b$ he only can drive once from $a$ to $b$, or drive once from $b$ to $a$, or do not use this road at all.
The wizards wants to plan as many episodes as possible without violation the above rules. Help the wizard!
Please note that the wizard can visit the same city multiple times, the restriction is on roads only.
|
Obviously the task can be solved independently for each component. Here is the algorithm that allows you to reach exactly $\lfloor{\frac{m}{2}}\rfloor$ tours, where $m$ is the number of edges in the component. Let's take arbitrary tree built by depth-first search. While exiting vertex $v$, we can process all the edges to the vertices with greater height and the edge connecting vertex $v$ to its parent in the tree (if $v$ isn't a root). If the number of edges to the lower vertices is even then we can split then into pairs. Otherwise let's add the edge from the parent to this splitting and not handle it for the parent itself. This algorithm will find the pair to every edge for all the vertices but the root. There will be at most one edge without the pair so the answer is maximal.
|
[
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,300
| null |
859
|
A
|
Declined Finalists
|
This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible contestant must either accept or decline the invitation. Whenever a contestant declines, the highest ranked contestant not yet invited is invited to take the place of the one that declined. This continues until 25 contestants have accepted invitations.
After the qualifying round completes, you know $K$ of the onsite finalists, as well as their qualifying ranks (which start at $1$, there are no ties). Determine the minimum possible number of contestants that declined the invitation to compete onsite in the final round.
|
If all ranks are 25 or less, then the answer is 0, since it's possible that all of the top 25 accepted the invitation. Otherwise, notice that the highest invited rank is initially 25, and increases by 1 every time a contestant declines. Therefore the answer is simply the highest rank minus 25.
|
[
"greedy",
"implementation"
] | 800
| null |
859
|
B
|
Lazy Security Guard
|
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly $N$ city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly $N$ blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.
|
Let's ask the problem a different way. For a fixed perimeter, what's the maximum number of city blocks we can fit in it? The maximum will always be achieved by a rectangle, because that's the only shape that doesn't contain any $270^{\circ}$ angles. A $270^{\circ}$ angle is not allowed because there would be a way to add another city block without affecting the perimeter. The problem is therefore equivalent to finding the minimum-perimeter rectangle with area at least $N$. A $H \times W$ rectangle has a perimeter of $2 \cdot (H + W)$. The constraints of the problem were low enough that one could loop through every possible value of $H$ and find the smallest corresponding $W$ such that $H \cdot W \ge N$. We can show that the best rectangle will always have $|W-H|\leq1$. Consider what happens if $W \ge H + 2$. Then $(W - 1) \cdot (H + 1) = W \cdot H + (W - H) - 1 \ge W \cdot H + (2) - 1 = W \cdot H + 1$. In other words, the $(W - 1) \times (H + 1)$ rectangle has greater area than the $W \times H$ rectangle, but the same perimeter. A direct solution therefore sets $W=\lceil{\sqrt{N}}\rceil$ and $H = \lceil N / W \rceil $.
|
[
"brute force",
"geometry",
"math"
] | 1,000
| null |
859
|
C
|
Pie Rules
|
You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person.
The way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the "decider" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left.
All of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive?
|
Denote $Score(L)$ as the total sizes of slices that will be eaten by whoever holds the decider token, for a list of pies $L$, and denote $Total(L)$ as the total size of all slices, and $Rest(L)$ as the list of pies formed by removing the first pie. Note that the total sizes of slices eaten by whoever doesn't hold the decider token is given by $Total(L) - Score(L)$. Let's consider the options available to the participant with the decider token. If they choose to take the pie for themselves, they end up with $L[0] + Total(Rest(L)) - Score(Rest(L))$ total pie. If they let the other participant have the slice, they end up with $Score(Rest(L))$ total pie. They will choose whichever option is larger. To compute the answer, we simply start from the end of the game and work backwards to the beginning.
|
[
"dp",
"games"
] | 1,500
| null |
859
|
D
|
Third Month Insanity
|
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of $2^{N}$ teams participating in the tournament, numbered from $1$ to $2^{N}$. The tournament lasts $N$ rounds, with each round eliminating half the teams. The first round consists of $2^{N - 1}$ games, numbered starting from $1$. In game $i$, team $2·i - 1$ will play against team $2·i$. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game $i$ the winner of the previous round's game $2·i - 1$ will play against the winner of the previous round's game $2·i$.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth $1$ point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth $2^{N - 1}$ points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
|
Denote $opp(r, t)$ as the set of teams that could play against team $t$ in round $r$, and $w[t][u]$ is the probability that team $t$ defeats team $u$. We would first like to compute the probability that team $t$ wins a game in round $r$, and call this $p[r][t]$. Set $p[0][t] = 1$ for all teams for convenience. Then for $r \ge 1$ we have that the probability $t$ wins a game in round $r$ is equal to the probability that they won a game in round $r - 1$, times the sum, over all opponents, of the probability of facing that opponent times the probability of defeating that opponent. In mathematical terms, $p[r][t]=p[r-1][t]*\sum_{u\in o p p(r,t)}p[r-1][u]*w[t][u]$. Now let us denote $S[r][t]$ as the maximum expected score that can be achieved after $r$ rounds, choosing team $t$ as a winner in round $r$, and only counting points scored in games played between teams that could play in the game that $t$ would play in in round $r$. In other words, consider the sub-bracket which contains $t$ but only goes for $r$ rounds. Our desired result is ${\underset{[\mathbf{R}[\mathbf{x}[\mathbf{x}]^{N}}}\left(S[\mathbf{N}][t]\right)$. Begin by setting $S[0][t] = 0$ for all $t$. Then for each round and team compute $S[r][t]=\operatorname*{max}_{u\in o p p(r,t)}(S[r-1][t]+S[r-1][u]+p[r][t]\wedge\stackrel{x}{2}^{r-1})$.
|
[
"dp",
"probabilities",
"trees"
] | 2,100
| null |
859
|
E
|
Desk Disorder
|
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.
How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo $1000000007 = 10^{9} + 7$.
|
Consider an undirected graph where the desks are vertices and the engineers are edges. For each engineer an edge connects their current desk to their desired desk. Each connected component of this graph can be assigned independently, with the final result being the product of the number of assignments over the individual components. What type of graphs are the connected components? We know because it's connected that $E \ge V - 1$, where $E$ and $V$ are number of edges and vertices, respectively. Also note that $E \le V$ due to the condition that no two engineers currently sit at the same desk. It follows that there are only 2 cases to consider. Case 1: $E = V - 1$. In this case the component is a tree. We claim that the number of assignments is equal to $V$ in this case. To see why this is true, consider that after we choose which of the $V$ desks to leave empty, there's always exactly 1 way to assign engineers to the remaining desks. Case 2: $E = V$. In this case the component has exactly one cycle. Engineers currently sitting at a desk on the cycle can either all stay at their current desk, or all move to their desired desk. Engineers currently sitting at a desk not on the cycle must remain at their current desks. Therefore there will be exactly 2 assignments, unless the cycle was a self-loop (an engineer whose desired desk is equal to their current desk), in which case there is only 1 assignment. To compute the result, we can use a Disjoint-set data structure. For each connected component, we keep track of its size and what type of cycle (if any) is present. Initially each desk is in a component by itself. For each engineer, we merge the components containing their current and desired desks, or mark the component as containing a cycle if the current and desired desks were already in the same component. Finally we multiply together the numbers of assignments of the components.
|
[
"combinatorics",
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,100
| null |
859
|
F
|
Ordering T-Shirts
|
It's another Start[c]up, and that means there are T-shirts to order. In order to make sure T-shirts are shipped as soon as possible, we've decided that this year we're going to order all of the necessary T-shirts before the actual competition. The top $C$ contestants are going to be awarded T-shirts, but we obviously don't know which contestants that will be. The plan is to get the T-Shirt sizes of all contestants before the actual competition, and then order enough T-shirts so that no matter who is in the top $C$ we'll have T-shirts available in order to award them.
In order to get the T-shirt sizes of the contestants, we will send out a survey. The survey will allow contestants to either specify a single desired T-shirt size, or two adjacent T-shirt sizes. If a contestant specifies two sizes, it means that they can be awarded either size.
As you can probably tell, this plan could require ordering a lot of unnecessary T-shirts. We'd like your help to determine the minimum number of T-shirts we'll need to order to ensure that we'll be able to award T-shirts no matter the outcome of the competition.
|
Let us first describe how to tell if a given set of T-shirts is sufficient to award the competitors. For any set of T-shirt sizes, it clearly must be the case that the total number of T-shirts ordered of sizes in the set must be at least as large as the maximum number of competitors that could require a T-shirt size from the set. We claim that this is sufficient as well, and will prove it using the max-flow min-cut theorem. Construct a flow graph with a source, one node for each type of survey response, one node for each T-shirt size, and a sink. Add an edge from the source to each survey response node with capacity equal to the number of winners with that response. Add an edge from each survey response to the corresponding T-shirt size(s) with unlimited capacity. Add an edge from each T-shirt size to the sink with capacity equal to the number of T-shirts ordered. Find a minimum cut in this graph. Then for any maximal contiguous range of T-shirt sizes in the cut, we can remove those T-shirt sizes from the cut and instead cut the corresponding survey responses. It follows that the cut consisting only of survey responses is minimal, and by the max-flow min-cut theorem, an assignment exists that awards all winners T-shirts. Note that we don't need to consider all sets of T-shirt sizes - only contiguous sets of T-shirts sizes are relevant. If a non-contiguous set of T-shirt sizes violates the constraint, then one of its contiguous subsections must also violate the constraint. In other words, if we order $t_{i}$ shirts of size $i$, we only need to satisfy $t_{i}+\ldots+t_{j}\geq m i n(c,s_{2i-1}+\ldots+s_{2j-1}),\forall\ 1\leq i\leq j\leq n$. We now will show that the algorithm that greedily orders as few of each T-shirt as possible, starting from the smallest size, produces an optimal result. Suppose, to the contrary, that a better solution exists, and consider the lexicographically smallest such solution. At the first point where the solutions differ, the optimal solution must order more T-shirts (due to the greedy nature of the algorithm). If we change the optimal solution by ordering one fewer of that size and one more of the next size up, the solution will remain valid. However this violates the lexicographical minimality of the solution, a contradiction. Our solution is for each index $j$ from $1$ to $n$, to set $t_{j}=\operatorname*{max}_{1\leq i\leq j}(m i n(c,s_{2i-1}+\dots+s_{2j-1})-(t_{i}+\dots+t_{j-1}))$. This can easily be done in $O(n^{2})$ time if we compute cumulative sums of $t$ and $s$. In order to solve it faster, we need to be able to quickly find the index $i$ that maximizes the above expression. First lets consider the indexes where $c < s_{2i - 1} + ... + s_{2j - 1}$. Because all $t$ terms are non-negative, we only need to consider the largest such $i$ for which this is true, which can be found in amortized constant time. Now consider indexes where $c \ge s_{2i - 1} + ... + s_{2j - 1}$. Denote $r[i][j] = (s_{2i - 1} + ... + s_{2j - 1}) - (t_{i} + ... + t_{j - 1})$. Notice that for indexes $i_{1}, i_{2} < j$, we have $r[i_{1}][j] - r[i_{2}][j] = r[i_{1}][j - 1] - r[i_{2}][j - 1]$. This implies that if $r[i_{1}][j] > r[i_{2}][j]$ for some index $j$, it is true for all valid indexes $j$. Create a list of indexes $l$ maintaining invariants $l[a]<l[b]\land r[l[a]][j]>r[l[b]][j]\forall a<b$. Delete entries from the front of $l$ whenever they no longer satisfy $c \ge s_{2i - 1} + ... + s_{2j - 1}$. Insert $j$ at the end of the list on every iteration, deleting other indexes from the back of the list as necessary in order to maintain the invariants. At each step, the index that maximizes $r[i][j]$ can be found at the front of the list. Using a doubly-ended queue for $l$ makes all of these operations amortized constant time, for a total runtime of $O(n)$.
|
[
"greedy"
] | 2,800
| null |
859
|
G
|
Circle of Numbers
|
$n$ evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number $k$. Then you may repeatedly select a set of $2$ or more points which are evenly spaced, and either increase all numbers at points in the set by $k$ or decrease all numbers at points in the set by $k$. You would like to eventually end up with all numbers equal to $0$. Is it possible?
A set of $2$ points is considered evenly spaced if they are diametrically opposed, and a set of $3$ or more points is considered evenly spaced if they form a regular polygon.
|
Construct polynomial $P(x) = s_{i} \cdot x^{i}$. For $p|n$ denote $Q_{p}(x) = 1 + x^{n / p} + x^{2n / p} + ... + x^{(p - 1)n / p} = (x^{n} - 1) / (x^{n / p} - 1)$. Our task is to determine if $P(x)$ can be written as a linear combination of $Q_{i}(x)$ polynomials. Bézout's Identity tells us that a solution exists if the greatest common divisor of the $Q_{i}(x)$ polynomials also divides $P(x)$, and the familiar Extended Euclidean Algorithm could be used to construct a solution if needed. Let's compute the GCD of the $Q_{i}(x)$ polynomials, and call it $G(x)$. Let $ \omega = e^{2 \pi i / n}$. Then $Q_{p}(x)=\prod_{0<i<n,\lnot p|i}(x-\omega^{i})$. Therefore $G(x)=\prod_{0<i<n,a c d(i,n)=1}(x-\omega^{i})$. This is equal to the Cyclotomic Polynomial $ \Phi _{n}(x)$. Directly testing $P(x)$ for divisibility by $G(x)$ is quite expensive. Instead, denote $F$ as the set of prime factors of $n$ and let $R(x)=\prod_{i\in F}(x^{n/i}-1)$. Note that for each $i$, $(x-\omega^{i})|R(x)\iff g c d(i,n)\neq1$. It follows that $G(x)|P(x)\iff(x^{n}-1)|P(x)\cdot R(x)$. The latter can be easily computed. Alternate solution: Note that a necessary condition is that if we place weights on each point equal in magnitude to the number, then the center of gravity must be at exactly the center of the circle. Attempting to compute the center of gravity numerically isn't guaranteed to work because it could be extremely close to the center (we were able to construct test cases where it was within $10^{ - 500}$ of the center). However, if we choose some integer $m$ relatively prime to $n$, and for each point $i$ move its number to point $m \cdot i$, then the answer does not change, but the center of gravity might. We can check the center of gravity numerically for several random $m$, and if it's ever not within the margin of numerical error then the answer must be no. In theory this could still fail but in practice it was always easy to find a value of $m$ where the center of gravity is quite far from the actual center. Another way to probabilistically test if the center of gravity is at the center is to choose a random prime $p$ such that $n|p - 1$, and a random $r$ such that $r^{n}\equiv1\mod p$. Then it must be the case that $P(r)\equiv0{\pmod{p}}$.
|
[
"math"
] | 3,000
| null |
860
|
E
|
Arkady and a Nobody-men
|
Arkady words in a large company. There are $n$ employees working in a system of a strict hierarchy. Namely, each employee, with an exception of the CEO, has exactly one immediate manager. The CEO is a manager (through a chain of immediate managers) of all employees.
Each employee has an integer rank. The CEO has rank equal to $1$, each other employee has rank equal to the rank of his immediate manager plus $1$.
Arkady has a good post in the company, however, he feels that he is nobody in the company's structure, and there are a lot of people who can replace him. He introduced the value of replaceability. Consider an employee $a$ and an employee $b$, the latter being manager of $a$ (not necessarily immediate). Then the replaceability $r(a, b)$ of $a$ with respect to $b$ is the number of subordinates (not necessarily immediate) of the manager $b$, whose rank is not greater than the rank of $a$. Apart from replaceability, Arkady introduced the value of negligibility. The negligibility $z_{a}$ of employee $a$ equals the sum of his replaceabilities with respect to all his managers, i.e. ${z_{a}}=\sum_{b}r(a,b)$, where the sum is taken over all his managers $b$.
Arkady is interested not only in negligibility of himself, but also in negligibility of all employees in the company. Find the negligibility of each employee for Arkady.
|
First of all, $ans[v] = ans[parent[v]] + depth[v] + ans'[v]$, where $ans'[v]$ is the sum of (number of descendants of the rank depth[v]) for all predecessors of $v$. All we need is to compute $ans'[v]$ now. Let's make a dfs in the graph. Let the dfs(v) return a vector $ret[v]$ such that $ret[v][d]$ is the following tuple: (number of vertices on depth $d$ in subtree of $v$, some vertex $x$ with depth $d$ in the subtree of $v$, the $ans'[x]$ if we consider only predecessors in the subtree of $v$). Also let's build some structure so that we can easily restore answers in this subtree if we know the final value of $ans'[x]$. We will see what is this structure later. To compute $ret[v]$ we need to be able to merge two $ret$s of its sons. Let's say we merge tuple $(cnt_{a}, a, ans'[a])$ with $(cnt_{b}, b, ans'[b])$. Then all we need to do is: $ans'[b] + = depth[v] * cnt_{a}$, $ans'[a] + = depth[v] * cnt_{b}$, return $(cnt_{a} + cnt_{b}, a, ans'[a])$ as the result. However, we must also be able to restore $ans'[b]$ after the dfs is complete (remind the unknown structure). So after performing $ans'[b] + = depth[v] * cnt_{a}$ let's add an edge $a \rightarrow b$ to a new graph with weight $ans'[a] - ans'[b]$. Note that the difference between these values will be the same all the time after the tuples are merged, so using this edge we will be able to restore the answer $ans'[b]$. After the dfs is done, run another dfs on the new graph to restore the values $ans'[v]$ and then $ans[v]$. To perform the second step fast, we need to note that we can always merge smaller $ret$s into larger, and move them in $O(1)$ into parents. Since each tuple is merged into a larger vector only once, this solution works in total in $O(n)$.
|
[
"data structures",
"dfs and similar",
"trees"
] | 2,700
| null |
862
|
A
|
Mahmoud and Ehab and the MEX
|
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.
Dr. Evil is interested in sets, He has a set of $n$ integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly $x$. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set ${0, 2, 4}$ is $1$ and the MEX of the set ${1, 2, 3}$ is $0$ .
Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?
|
One can see that in the final set all the elements less than $x$ should exist, $x$ shouldn't exist and any element greater than $x$ doesn't matter, so we will count the number of elements less than $x$ that don't exist in the initial set and add this to the answer, If $x$ exists we'll add 1 to the answer because $x$ should be removed . Time complexity : $O(n + x)$ .
|
[
"greedy",
"implementation"
] | 1,000
|
"#include <iostream>\nusing namespace std;\nbool b[105];\nint main()\n{\n\tint n,x;\n\tscanf(\"%d%d\",&n,&x);\n\twhile (n--)\n\t{\n\t\tint a;\n\t\tscanf(\"%d\",&a);\n\t\tb[a]=1;\n\t}\n\tint ans=b[x];\n\tfor (int i=0;i<x;i++)\n\tans+=!b[i];\n\tprintf(\"%d\",ans);\n}"
|
862
|
B
|
Mahmoud and Ehab and the bipartiteness
|
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into $2$ sets in such a way, that for each edge $(u, v)$ that belongs to the graph, $u$ and $v$ belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of $n$ nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. \textbf{A cycle and a loop aren't the same} .
|
The tree itself is bipartite so we can run a dfs to partition the tree into the 2 sets (called bicoloring), We can't add an edge between any 2 nodes in the same set and we can add an edge between every 2 nodes in different sets, so let the number of nodes in the left set be $l$ and the number of nodes in the right set be $r$, The maximum number of edges that can exist is $l * r$, but $n - 1$ edges already exist so the maximum number of edges to be added is $l * r - (n - 1)$. Time complexity : $O(n)$ .
|
[
"dfs and similar",
"graphs",
"trees"
] | 1,300
|
"#include <iostream>\n#include <vector>\nusing namespace std;\nvector<int> v[100005];\nlong long cnt[2];\nvoid dfs(int node,int pnode,int color)\n{\n\tcnt[color]++;\n\tfor (int i=0;i<v[node].size();i++)\n\t{\n\t\tif (v[node][i]!=pnode)\n\t\tdfs(v[node][i],node,!color);\n\t}\n}\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=1;i<n;i++)\n\t{\n\t\tint a,b;\n\t\tscanf(\"%d%d\",&a,&b);\n\t\tv[a].push_back(b);\n\t\tv[b].push_back(a);\n\t}\n\tdfs(1,0,0);\n\tprintf(\"%I64d\",cnt[0]*cnt[1]-n+1);\n}"
|
862
|
C
|
Mahmoud and Ehab and the xor
|
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer $x$. He asks Mahmoud and Ehab to find a set of $n$ distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly $x$. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than $10^{6}$.
|
$n = 2, x = 0$ is the only case with answer "NO" . Let $pw = 2^{17}$ . First print $1, 2, ..., n - 3$ (The first $n - 3$ positive integers), Let their bitwise-xor sum be $y$, If $x = y$ You can add $pw, pw * 2$ and $p w\oplus(p w*2)$, Otherwise you can add $0, pw$ and $p w\oplus x\oplus y$, We handled the case $x = y$ in a different way because if we add $0, pw$ and $p w\oplus x\oplus y$ in this case, Then it's like adding $0, pw$ and $pw$, $pw$ appears twice so we'll get wrong answer. Handle $n = 1$ (print $x$) and $n = 2$ (print $0$ and $x$) .
|
[
"constructive algorithms"
] | 1,900
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int pw1=(1<<17);\nconst int pw2=(1<<18);\n\nint main()\n{\n\tint n,x;\n\tcin >> n >> x;\n\tif(n==1)\n\t\tcout << \"YES\\n\"<<x<<\"\\n\";\n\telse if(n==2&&x==0)\n\t\tcout << \"NO\\n\";\n\telse if(n==2)\n\t\tcout << \"YES\\n0 \"<<x<<\"\\n\";\n\telse\n\t{\n\t\tint i;\n\t\tint ans=0;\n\t\tcout << \"YES\\n\";\n\t\tfor(i=1;i<=n-3;i++)\n\t\t{\n\t\t\tcout << i << \" \";\n\t\t\tans^=i;\n\t\t}\n\t\tif(ans==x)\n\t\t\tcout << pw1+pw2 << \" \" << pw1 << \" \" << pw2<< \"\\n\";\n\t\telse\n\t\t\tcout << pw1 << \" \" << ((pw1^x)^ans) << \" 0 \\n\";\n\t}\n}"
|
862
|
D
|
Mahmoud and Ehab and the binary string
|
Mahmoud and Ehab are in the fourth stage now.
Dr. Evil has a hidden binary string of length $n$. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to $15$ questions. They tell Dr. Evil some binary string of length $n$, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below.
Help Mahmoud and Ehab find these two positions.
You will get Wrong Answer verdict if
- Your queries doesn't satisfy interaction protocol described below.
- You ask strictly more than $15$ questions and your program terminated after exceeding queries limit. Please note, that you can do up to $15$ ask queries and one answer query.
- Your final answer is not correct.
You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .
|
In the editorial we suppose that the answer of some query is the number of correct guessed positions which is equal to $n$ minus hamming distance, The solutions in this editorial consider the answer of a query as $n$ minus real answer, For convenience. Common things : Let $zero(l, r)$ be a function that returns the number of zeros in the interval $[l;r]$ minus the number of ones in it, We can find it in one query after a preprocessing query, The preprocessing query is $1111...$, Let its answer be stored in $all$, If we made a query with a string full of ones except for the interval $[l;r]$ which will be full of zeros, If this query's answer is $cur$, $zero(l, r) = cur - all$, That's because $all$ is the number of ones in the interval $[l;r]$ plus some trash and $cur$ is the number of zeros in the interval plus the same trash . Let's have a searching interval, initially this interval is $[1;n]$ (The whole string), Let's repeat this until we reach our goal, Let $mid = (l + r) / 2$ Let's query to get $zero(l, mid)$, If it's equal to $r - l + 1$, This interval is full of zeros so we can print any index in it as the index with value 0 and continue searching for an index with the value 1 in the interval $[mid + 1;r]$, But if its value is equal to $l - r - 1$, This interval is full of ones so we can print any index in it as the index with value 1 and continue searching for a 0 in the interval $[mid + 1;r]$, Otherwise the interval contains both values so we can continue searching for both in the interval $[l;mid]$, Every time the searching interval length must be divided by 2 in any case so we perform $O(log(n))$ queries . Let's send $1111...$ and let the answer be $ans1$, Let's send $0111...$ and let the answer be $ans0$, We now know the value in the first index (1 if $ans1 > ans0$, 0 otherwise), We can binary search for the first index where the non-found value exists, which is to binary search on the first value $x$ where $zero(2, x) * sign(non - found$ $bit$ $value) \neq x - 1$ where $sign(y)$ is $1$ if $y = 0$, $- 1$ otherwise .
|
[
"binary search",
"divide and conquer",
"interactive"
] | 2,000
|
"#include <iostream>\nusing namespace std;\nchar s[1005];\nint ans,pos0,pos1,n;\nvoid send()\n{\n\tprintf(\"? %s\\n\",s);\n\tfflush(stdout);\n\tscanf(\"%d\",&ans);\n\tans=n-ans;\n}\nint main()\n{\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<n;i++)\n\ts[i]='1';\n\tsend();\n\tint mans=ans;\n\ts[0]='0';\n\tsend();\n\tif (mans>ans)\n\tpos1=1;\n\telse\n\tpos0=1;\n\ts[0]='1';\n\tint st=1,en=n;\n\twhile (st!=en)\n\t{\n\t\tint mid=(st+en)/2;\n\t\tfor (int i=1;i<=mid;i++)\n\t\ts[i]='0';\n\t\tsend();\n\t\tif ((mans-ans)*(pos1? 1:-1)==mid)\n\t\tst=mid+1;\n\t\telse\n\t\ten=mid;\n\t\tfor (int i=1;i<=mid;i++)\n\t\ts[i]='1';\n\t}\n\tif (!pos0)\n\tpos0=st+1;\n\telse\n\tpos1=st+1;\n\tprintf(\"! %d %d\",pos0,pos1);\n\tfflush(stdout);\n}"
|
862
|
E
|
Mahmoud and Ehab and the function
|
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array $a$ of length $n$ and array $b$ of length $m$. He introduced a function $f(j)$ which is defined for integers $j$, which satisfy $0 ≤ j ≤ m - n$. Suppose, $c_{i} = a_{i} - b_{i + j}$. Then $f(j) = |c_{1} - c_{2} + c_{3} - c_{4}... c_{n}|$. More formally, $f(j)=|\sum_{i=1}^{n}(-1)^{i-1}*(a_{i}-b_{i+j})|$.
Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid $j$. They found it a bit easy, so Dr. Evil made their task harder. He will give them $q$ update queries. During each update they should add an integer $x_{i}$ to all elements in $a$ in range $[l_{i};r_{i}]$ i.e. they should add $x_{i}$ to $a_{li}, a_{li + 1}, ... , a_{ri}$ and then they should calculate the minimum value of $f(j)$ for all valid $j$.
Please help Mahmoud and Ehab.
|
Let's write $f(j)$ in another way:- $f(j)=\vert\sum_{i=1}^{n}(-1)^{i-1}*(a_{i}-b_{i+j})\vert=\vert\sum_{i=1}^{n}(-1)^{i-1}*a_{i}+(-1)^{i}*b_{i+j}\vert$ $=\left|\sum_{i=1}^{n}(-1)^{i-1}\ast a_{i}+\sum_{i=1}^{n}(-1)^{i}\ast b_{i+j}\right|$ Now we have 2 sums, The first one is constant (doesn't depend on $j$), For the second sum we can calculate all its possible values using sliding window technique, Now we want a data-structure that takes the value of the first sum and chooses the best second sum from all the choices . observation: We don't have to try all the possible values of $f(j)$ to minimize the expression, If the first sum is $c$, We can try only the least value greater than $- c$ and the greatest value less than $- c$ ($- c$ not $c$ because we are minimizing $c + second$ not $c - second$) because the absolute value means the distance between the two values on the number line, Any other value will be further than at least one of the chosen values, To do this we can keep all the values of $f(j)$ sorted and try the elements numbered lower_bound(-c) and lower_bound(-c)-1 and choose the better (In short we're trying the values close to $- c$ only). Now we have a data-structure that can get us the minimum value of the expression once given the value of the first sum in $O(log(n))$, Now we want to keep track of the value of the first sum . Let the initial value be $c$, In each update, If the length of the updated interval is even, The sum won't change because $x$ will be added as many times as it's subtracted, Otherwise $x$ will be added to $c$ or subtracted from $c$ depending of the parity of $l$ (the left-bound of the interval) . Time complexity : $O(n + (m + q)log(m))$ .
|
[
"binary search",
"data structures",
"sortings"
] | 2,100
|
"#include <iostream>\n#include <set>\nusing namespace std;\nint sign(int x)\n{\n\tif (x%2)\n\treturn -1;\n\treturn 1;\n}\nlong long absll(long long x)\n{\n\tif (x>0)\n\treturn x;\n\treturn -x;\n}\nset<long long> s;\nint b[100005];\nlong long ans(long long x)\n{\n\tset<long long>::iterator it=s.lower_bound(x);\n\tif (it==s.end())\n\tit--;\n\tlong long ret=absll((*it)-x);\n\tif (it!=s.begin())\n\tit--;\n\treturn min(ret,absll((*it)-x));\n}\nint main()\n{\n\tint n,m,q;\n\tscanf(\"%d%d%d\",&n,&m,&q);\n\tlong long sumA=0;\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tint a;\n\t\tscanf(\"%d\",&a);\n\t\tsumA+=a*sign(i);\n\t}\n\tlong long cur=0;\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tscanf(\"%d\",&b[i]);\n\t\tcur+=sign(i+1)*b[i];\n\t}\n\ts.insert(cur);\n\tfor (int i=n;i<m;i++)\n\t{\n\t\tscanf(\"%d\",&b[i]);\n\t\tcur+=b[i-n];\n\t\tcur=-cur;\n\t\tcur+=sign(n)*b[i];\n\t\ts.insert(cur);\n\t}\n\tprintf(\"%I64d\\n\",ans(-sumA));\n\twhile (q--)\n\t{\n\t\tint l,r,x;\n\t\tscanf(\"%d%d%d\",&l,&r,&x);\n\t\tif ((r-l)%2==0)\n\t\t{\n\t\t\tif (l%2)\n\t\t\tsumA+=x;\n\t\t\telse\n\t\t\tsumA-=x;\n\t\t}\n\t\tprintf(\"%I64d\\n\",ans(-sumA));\n\t}\n}"
|
862
|
F
|
Mahmoud and Ehab and the final stage
|
Mahmoud and Ehab solved Dr. Evil's questions so he gave them the password of the door of the evil land. When they tried to open the door using it, the door gave them a final question to solve before they leave (yes, the door is digital, Dr. Evil is modern). If they don't solve it, all the work will be useless and they won't leave the evil land forever. Will you help them?
Mahmoud and Ehab are given $n$ strings $s_{1}, s_{2}, ... , s_{n}$ numbered from $1$ to $n$ and $q$ queries, Each query has one of the following forms:
- $1$ $a$ $b$ $(1 ≤ a ≤ b ≤ n)$, For all the intervals $[l;r]$ where $(a ≤ l ≤ r ≤ b)$ find the maximum value of this expression:$(r - l + 1) * LCP(s_{l}, s_{l + 1}, ... , s_{r - 1}, s_{r})$ where $LCP(str_{1}, str_{2}, str_{3}, ... )$ is the length of the longest common prefix of the strings $str_{1}, str_{2}, str_{3}, ... $.
- $2$ $x$ $y$ $(1 ≤ x ≤ n)$ where $y$ is a string, consisting of lowercase English letters. Change the string at position $x$ to $y$.
|
First, Let's get rid of the $LCP$ part . observation: $L C P(s t r_{1},s t r_{2},\cdot\cdot\cdot,s t r_{k})=\operatorname*{min}_{i=1}^{k-1}L C P(s t r_{i},s t r_{i+1})$, That could make us transform the $LCP$ part into a minimization part by making an array $lcp$ where $lcp_{i} = LCP(s_{i}, s_{i + 1})$, You could calculate it naively, And when an update happens at index $a$, You should update $lcp_{a}$ (If exists) and $lcp_{a - 1}$ (If exists) naively . Now the problem reduces to finding $a \le l \le r \le b$ that maximizes the value:- $(\operatorname*{min}_{i=l}l c p_{i})*(r-l+1)$, If we have a histogram where the $i^{th}$ column has height $lcp_{i}$, The the size of the largest rectangle that fits in the columns from $l$ to $r - 1$ is $(\operatorname*{min}_{i=l}l c p_{i})*(r-l)$, That's close to our formula not the same but it's not a problem (You'll see how to fix it later), so to get rid of finding the $l$ and $r$ part, We can make that histogram and the answer for a query will be the largest rectangle in the subhistogram that contains the columns from $a$ to $b - 1$, One of the ways to solve it is to try some heights $h$ and see the maximum width we can achieve if $h$ was the height, call it $w$, and maximize with $h * w$, To solve the slight difference in formulas problem we'll just maximize with $h * (w + 1)$!! Let $BU$ be a value the we'll choose later, We have 2 cases for our largest rectangle's height $h$, It could be either $h \le BU$ or $h > BU$, We will solve both problems separately. For $h \le BU$ we can maintain $BU$ segment trees, Segment tree number $i$ has $1$ at index $x$ if $lcp_{x} \ge i$ and $0$ otherwise, When we query, It should get us the longest subsegment of ones in the query range, Let's see what we need for our merging operation, If we want the answer for the longest subsegment of ones in a range $[l;r]$, Let $mid = (l + r) / 2$, Then the answer is the maximum between the answer of $[l;mid]$, The answer of $[mid + 1;r]$, And the maximum suffix of ones in the range $[l;mid]$ added to the maximum prefix of ones in the range $[mid + 1;r]$ . So we need to keep all these information in our node and also the length of the interval, As it's a well-known problem I won't get into more detail. Back to our problem, We can loop over all $h \le BU$, Let the answer for the query on range $[a;b - 1]$ in segment tree number $h$ be $w$, The maximum width of a rectangle of height $h$ in this range is $w$ and we'll maximize our answer with $h * (w + 1)$ . For $h > BU$, Let's call a column of height greater than $BU$ big, The heights we'll try are the heights of the big columns in the range, We don't have to try all the heights greater the $BU$, There are at most $\frac{t o t}{B U}$ big columns (Where $tot$ is the total length of strings in input), Let's keep them in a set, When an update happens, You should add the column to the set or remove it depending on its new height, The set's size can't exceed $\frac{t o t}{B U}$ now, Let's see how to answer a query, Let's loop over the big columns in range $[a;b - 1]$ only, If 2 of them aren't consecutive then the column after the first can't be big and the column before the second either, That's because if it were big, It would be in our set, So we can use this observation by making a new histogram with the big columns in the range only, And put a column with height 0 between any non-consecutive two, And get the largest rectangle in this histogram by the stack way for example in $O(\underline{{{\scriptscriptstyle(L d I)}}}^{i d I})$, The stack way will get us the maximum width $w$ we can achieve for a rectangle containing column number $i$, We'll maximize with $lcp_{i} * (w + 1)$. Also the answer for our main formula can be an interval of length one, All what I mentioned doesn't cover this, You should maintain another segment tree that gets the maximum length of a string in a range for this . Maximize all what we got, You have the answer, Now it's time to choose $BU$, It's optimal in time to choose $BU$ near $\sqrt{{\frac{t o t}{i\omega g(t o t)}}}$ (Reason in tfg's comment below) . Optimization: The longest subsegment of ones problem is solved by $BU$ segment trees and each one has 4 integers in each node, You can make them 2 integers (max prefix and suffix of ones) and make another only one segment tree that has the rest of the integers, That would divide the memory by 2 . Time complexity : $O(t o t+q{\sqrt{t o t*l o g(t o t)}})$
|
[
"data structures",
"strings"
] | 2,900
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\nconst int BUBEN = (int)110;\n\nstruct Data {\n int goLeft[BUBEN], goRight[BUBEN];\n int res;\n int length;\n Data(int x) {\n x = min(x, BUBEN - 1);\n res = x;\n length = 1;\n for (int i = 0; i < BUBEN; i++) {\n if (i <= x) {\n goLeft[i] = goRight[i] = 1;\n } else {\n goLeft[i] = goRight[i] = 0;\n }\n }\n }\n Data() {}\n};\n\nvoid merge(const Data &l, const Data &r, Data &res) {\n res.res = max(l.res, r.res);\n res.length = l.length + r.length;\n for (int i = 0; i < BUBEN; i++) {\n res.goLeft[i] = l.goLeft[i];\n if (res.goLeft[i] == l.length) res.goLeft[i] += r.goLeft[i];\n res.goRight[i] = r.goRight[i];\n if (res.goRight[i] == r.length) res.goRight[i] += l.goRight[i];\n if (r.goLeft[i] || l.goRight[i]) {\n res.res = max(res.res, i * (r.goLeft[i] + l.goRight[i] + 1));\n }\n }\n}\n\nstruct SegmentTree {\n Data *t;\n Data tmp, tmp2;\n int n;\n SegmentTree(int n) : n(n) {\n t = new Data[4 * n + 3];\n }\n SegmentTree() {}\n void change(int v, int tl, int tr, int pos, int val) {\n if (tl == tr) {\n t[v] = Data(val);\n } else {\n int tm = (tl + tr) >> 1;\n if (pos <= tm) {\n change(v + v, tl, tm, pos, val);\n } else {\n change(v + v + 1, tm + 1, tr, pos, val);\n }\n merge(t[v + v], t[v + v + 1], t[v]);\n }\n }\n void build(int v, int tl, int tr, int *a) {\n if (tl == tr) {\n t[v] = Data(a[tl]);\n } else {\n int tm = (tl + tr) >> 1;\n build(v + v, tl, tm, a);\n build(v + v + 1, tm + 1, tr, a);\n merge(t[v + v], t[v + v + 1], t[v]);\n }\n }\n void build(int *a) {\n build(1, 1, n, a);\n }\n void change(int pos, int val) {\n change(1, 1, n, pos, val);\n }\n void get(int v, int tl, int tr, int l, int r) {\n if (r < tl || l > tr) return;\n if (tl >= l && tr <= r) {\n merge(tmp, t[v], tmp2);\n memcpy(&tmp, &tmp2, sizeof(tmp));\n } else {\n int tm = (tl + tr) >> 1;\n get(v + v, tl, tm, l, r);\n get(v + v + 1, tm + 1, tr, l, r);\n }\n }\n int solve(int l, int r) {\n memset(&tmp, 0, sizeof(tmp));\n memset(&tmp2, 0, sizeof(tmp2));\n get(1, 1, n, l, r);\n return tmp.res;\n }\n};\n\n\nint solveHistogram(const vector<int> &a) {\n int n = (int)a.size();\n vector<int> gol(n), gor(n);\n vector<int> st;\n st.reserve(n);\n for (int i = 0; i < n; i++) {\n while (!st.empty() && a[st.back()] >= a[i]) st.pop_back();\n if (st.empty()) {\n gol[i] = 0;\n } else {\n gol[i] = st.back() + 1;\n }\n st.push_back(i);\n }\n st.clear();\n for (int i = n - 1; i >= 0; i--) {\n while (!st.empty() && a[st.back()] >= a[i]) st.pop_back();\n if (st.empty()) {\n gor[i] = n - 1;\n } else {\n gor[i] = st.back() - 1;\n }\n st.push_back(i);\n }\n int res = 0;\n for (int i = 0; i < n; i++) {\n res = max(res, a[i] * (gor[i] - gol[i] + 2));\n }\n return res;\n}\n\nstruct LargeSolver {\n int *a;\n int n;\n set<int> largePoses;\n LargeSolver(int n) : n(n) {\n a = new int[n + 1];\n }\n LargeSolver() {}\n void change(int pos, int val) {\n if (a[pos] >= BUBEN) {\n largePoses.erase(pos);\n }\n a[pos] = val;\n if (a[pos] >= BUBEN) {\n largePoses.insert(pos);\n }\n }\n int solve(int l, int r) {\n auto it = largePoses.lower_bound(l);\n int res = 0;\n vector<int> cur;\n int lst = -1;\n while (it != largePoses.end() && (*it) <= r) {\n int curPos = (*it);\n if (curPos != lst + 1 && !cur.empty()) {\n res = max(res, solveHistogram(cur));\n cur.clear();\n }\n cur.push_back(a[curPos]);\n lst = curPos;\n it++;\n }\n if (!cur.empty()) {\n res = max(res, solveHistogram(cur));\n }\n return res;\n }\n};\n\nstruct MaxSegmentTree {\n int *t;\n int n;\n MaxSegmentTree(int n) : n(n) {\n t = new int[4 * n + 3];\n }\n MaxSegmentTree() {}\n void change(int v, int tl, int tr, int pos, int val) {\n if (tl == tr) {\n t[v] = val;\n } else {\n int tm = (tl + tr) >> 1;\n if (pos <= tm) {\n change(v + v, tl, tm, pos, val);\n } else {\n change(v + v + 1, tm + 1, tr, pos, val);\n }\n t[v] = max(t[v + v], t[v + v + 1]);\n }\n }\n void change(int pos, int val) {\n change(1, 1, n, pos, val);\n }\n int getMax(int v, int tl, int tr, int l, int r) {\n if (r < tl || l > tr) return 0;\n if (tl >= l && tr <= r) return t[v];\n int tm = (tl + tr) >> 1;\n return max(getMax(v + v, tl, tm, l, r), getMax(v + v + 1, tm + 1, tr, l, r));\n }\n int getMax(int l, int r) {\n return getMax(1, 1, n, l, r);\n }\n};\n\nstruct DynamicHystogramSolver {\n SegmentTree st;\n LargeSolver ls;\n DynamicHystogramSolver() {}\n DynamicHystogramSolver(int *a, int n) {\n st = SegmentTree(n);\n st.build(a);\n ls = LargeSolver(n);\n for (int i = 1; i <= n; i++) {\n ls.change(i, a[i]);\n }\n }\n void change(int pos, int val) {\n st.change(pos, val);\n ls.change(pos, val);\n }\n int getMax(int l, int r) {\n if (l > r) return 0;\n return max(st.solve(l, r), ls.solve(l, r));\n }\n};\n\nint getLCP(const string &s, const string &t) {\n int ptr = 0;\n while (ptr < (int)min(s.size(), t.size()) && s[ptr] == t[ptr]) ptr++;\n return ptr;\n}\nstruct Solver {\n string *s;\n int *lcp;\n int n;\n DynamicHystogramSolver dhs;\n MaxSegmentTree st;\n Solver(const vector<string> &a) {\n n = a.size();\n s = new string[n + 1];\n lcp = new int[n + 1];\n for (int i = 1; i <= n; i++) {\n s[i] = a[i - 1];\n }\n for (int i = 1; i < n; i++) {\n lcp[i] = getLCP(s[i], s[i + 1]);\n }\n dhs = DynamicHystogramSolver(lcp, n);\n st = MaxSegmentTree(n);\n for (int i = 1; i <= n; i++) {\n st.change(i, (int)s[i].size());\n }\n }\n void change(int pos, const string &str) {\n s[pos] = str;\n if (pos != 1) {\n lcp[pos - 1] = getLCP(s[pos - 1], s[pos]);\n dhs.change(pos - 1, lcp[pos - 1]);\n }\n if (pos != n) {\n lcp[pos] = getLCP(s[pos], s[pos + 1]);\n dhs.change(pos, lcp[pos]);\n }\n st.change(pos, (int)str.size());\n }\n int solve(int l, int r) {\n return max(dhs.getMax(l, r - 1), st.getMax(l, r));\n }\n};\n\nconst int MX = 300 * 1000 + 7;\n\nchar buf[MX];\n\nstring getString() {\n scanf(\"%s\", buf);\n return string(buf);\n}\n\nint main() {\n#ifdef LOCAL\n freopen(\"input.txt\", \"r\", stdin);\n#endif\n int n, q;\n scanf(\"%d %d\", &n, &q);\n vector<string> s(n);\n for (int i = 0; i < n; i++) {\n s[i] = getString();\n }\n Solver solver(s);\n for (int i = 0; i < q; i++) {\n int type;\n scanf(\"%d\", &type);\n if (type == 1) {\n int l, r;\n scanf(\"%d %d\", &l, &r);\n printf(\"%d\\n\", solver.solve(l, r));\n } else {\n int pos;\n scanf(\"%d \", &pos);\n solver.change(pos, getString());\n }\n }\n return 0;\n}"
|
863
|
A
|
Quasi-palindrome
|
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String $t$ is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers $131$ and $2010200$ are quasi-palindromic, they can be transformed to strings "$131$" and "$002010200$", respectively, which are palindromes.
You are given some integer number $x$. Check if it's a quasi-palindromic number.
|
You can check if the given is quasi-palindromic by removing all the trailing zeros and checking if resulting string is a palindrome.
|
[
"brute force",
"implementation"
] | 900
| null |
863
|
B
|
Kayaking
|
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are $2·n$ people in the group (including Vadim), and they have exactly $n - 1$ tandem kayaks (each of which, obviously, can carry two people) and $2$ single kayaks. $i$-th person's weight is $w_{i}$, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.
Formally, the instability of a single kayak is always $0$, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.
Help the party to determine minimum possible total instability!
|
Firstly let's learn how to split persons in pairs as if there are no single kayaks. Let there be people with weights $a$, $b$, $c$ and $d$ ($a \le b \le c \le d$). Obviously, the lowest instability you can achieve is $max(b - a, d - c)$. Swapping any two elements will only make the result greater. This greedy strategy can be used to distribute all the seats. Now you need to check every pair of persons to seat in single kayaks and calculate total instability for the rest. The answer will be the minimun instabily over all pairs. Overall complexity: $O(n^{3})$.
|
[
"brute force",
"greedy",
"sortings"
] | 1,500
| null |
863
|
C
|
1-2-3
|
Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice".
So now Ilya wants to compare his robots' performance in a simple game called "1-2-3". This game is similar to the "Rock-Paper-Scissors" game: both robots secretly choose a number from the set ${1, 2, 3}$ and say it at the same moment. If both robots choose the same number, then it's a draw and noone gets any points. But if chosen numbers are different, then one of the robots gets a point: $3$ beats $2$, $2$ beats $1$ and $1$ beats $3$.
Both robots' programs make them choose their numbers in such a way that their choice in $(i + 1)$-th game depends only on the numbers chosen by them in $i$-th game.
Ilya knows that the robots will play $k$ games, Alice will choose number $a$ in the first game, and Bob will choose $b$ in the first game. He also knows both robots' programs and can tell what each robot will choose depending on their choices in previous game. Ilya doesn't want to wait until robots play all $k$ games, so he asks you to predict the number of points they will have after the final game.
|
Notice that there are only $9$ possible patterns in this game. You can used in a following way. Simulate games till one of the patterns get repeated. Games between this pair of occurences will get you the same total outcome no matter when they are played. Let the distance between the games with the same pattern is $dif$ and index of these games are $idx_{1}$ and $idx_{2}$ (zero-indexed). Total score of some interval is $score(l, r)$. Then the answer will be $score(0, idx_{1})$ + $\lfloor{\frac{k-i d x_{1}}{d i J}}\rfloor\cdot s c o r e(i d x_{1}+1,i d x_{2})$ + $((k - idx_{1})$ $mod$ $dif) \cdot score(idx_{1} + 1, idx_{1} + (k - idx_{1})$ $mod$ $dif)$.
|
[
"graphs",
"implementation"
] | 1,800
| null |
863
|
D
|
Yet Another Array Queries Problem
|
You are given an array $a$ of size $n$, and $q$ queries to it. There are queries of two types:
- $1$ $l_{i}$ $r_{i}$ — perform a cyclic shift of the segment $[l_{i}, r_{i}]$ to the right. That is, for every $x$ such that $l_{i} ≤ x < r_{i}$ new value of $a_{x + 1}$ becomes equal to old value of $a_{x}$, and new value of $a_{li}$ becomes equal to old value of $a_{ri}$;
- $2$ $l_{i}$ $r_{i}$ — reverse the segment $[l_{i}, r_{i}]$.
There are $m$ important indices in the array $b_{1}$, $b_{2}$, ..., $b_{m}$. For each $i$ such that $1 ≤ i ≤ m$ you have to output the number that will have index $b_{i}$ in the array after all queries are performed.
|
One can guess from the constraits that complexity of the algorithm should be either $O(nm + q)$ or $O(qm)$. And there is a solution with the second one. Let's try to solve the reversed problem - answer what position will some number be at after all the queries. Check the impact of some query on position $pos$. Let the query be on some segment $[l, r]$. If $pos$ is outside this segment then you can skip it. Otherwise reverse will swap $a_{pos}$ and $a_{r - (pos - l)}$, shift will swap $a_{pos}$ and $a_{pos - 1}$ (if $pos = l$ then it will be $r$ instead of $(pos - 1)$). This task can be translated to the given one just by reversing the query list. Overall complexity: $O(qm)$. Obviously, you can also solve it with Cartesian tree online in $O(n+(q+m))\log n)$.
|
[
"data structures",
"implementation"
] | 1,800
| null |
863
|
E
|
Turn Off The TV
|
Luba needs your help again! Luba has $n$ TV sets. She knows that $i$-th TV set will be working from moment of time $l_{i}$ till moment $r_{i}$, inclusive.
Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of \textbf{integer} moments of time when at least one of TV sets is working won't decrease. Luba will be very upset if she has to switch off a non-redundant TV set.
Help Luba by telling her the index of some redundant TV set. If there is no any, print -1.
|
Firstly let's compress the moments of time. Note that storing only $l$ and $r$ isn't enough (consider pairs ($[1, 2], [3, 4]$) and ($[1, 2], [4, 5]$)), you also should take $(l - 1)$. Now moments of time are up to $6 \cdot 10^{5}$. For every moment calculate the number of segments to cover it (make $cnt_{l} + = 1$ and $cnt_{r + 1} - = 1$ for each segment and take prefix sums over this array). Then let $pref_{i}$ be the number of moments of time covered by only one segment on some prefix up to $i$-th moment. And finally if for some segment $[l, r]$ from the input $pref_{r} - pref_{l - 1}$ is $0$ then you can safely delete this segment. Overall complexity: $O(n\log n)$.
|
[
"data structures",
"sortings"
] | 2,000
| null |
863
|
F
|
Almost Permutation
|
Recently Ivan noticed an array $a$ while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug.
Ivan clearly remembers that there were $n$ elements in the array, and each element was not less than $1$ and not greater than $n$. Also he remembers $q$ facts about the array. There are two types of facts that Ivan remembers:
- $1$ $l_{i}$ $r_{i}$ $v_{i}$ — for each $x$ such that $l_{i} ≤ x ≤ r_{i}$ $a_{x} ≥ v_{i}$;
- $2$ $l_{i}$ $r_{i}$ $v_{i}$ — for each $x$ such that $l_{i} ≤ x ≤ r_{i}$ $a_{x} ≤ v_{i}$.
Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the $q$ facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the $cost$ of array as follows:
$c o s t=\sum_{i=1}^{n}(c n t(i))^{2}$, where $cnt(i)$ is the number of occurences of $i$ in the array.
Help Ivan to determine minimum possible $cost$ of the array that corresponds to the facts!
|
This problem can be solved with mincost maxflow approach. Let's construct a following network: Construct a vertex for every number from $1$ to $n$. For each of these vertices add $n$ directed edges from the source to this vertex, the capacity of each edge will be $1$, and the costs will be $1, 3, 5, ..., 2n - 1$ (so pushing $k$ flow from the source to the vertex will cost exactly $k^{2}$); Also construct a vertex for every index of the array. For each number make add a directed edge with capacity $1$ and cost $0$ to every position in the array such that this number can be put into this position, and for every index make a directed edge from the vertex constructed for this index to the sink with capacity $1$ and cost $0$. Minimum cost maximum flow in this network will construct a suitable array with minimum cost, so the answer to the problem is minimum cost of maximum flow in the network.
|
[
"flows"
] | 2,200
| null |
863
|
G
|
Graphic Settings
|
Recently Ivan bought a new computer. Excited, he unpacked it and installed his favourite game. With his old computer Ivan had to choose the worst possible graphic settings (because otherwise the framerate would be really low), but now he wants to check, maybe his new computer can perform well even with the best possible graphics?
There are $m$ graphics parameters in the game. $i$-th parameter can be set to any positive integer from $1$ to $a_{i}$, and initially is set to $b_{i}$ ($b_{i} ≤ a_{i}$). So there are $p=\prod_{i=1}^{m}a_{i}$ different combinations of parameters. Ivan can increase or decrease any of these parameters by $1$; after that the game will be restarted with new parameters (and Ivan will have the opportunity to check chosen combination of parameters).
Ivan wants to try all $p$ possible combinations. Also he wants to return to the initial settings after trying all combinations, because he thinks that initial settings can be somehow best suited for his hardware. But Ivan doesn't really want to make a lot of restarts.
So he wants you to tell the following:
- If there exists a way to make exactly $p$ changes (each change either decreases or increases some parameter by $1$) to try all possible combinations and return to initial combination, then Ivan wants to know this way.
- Otherwise, if there exists a way to make exactly $p - 1$ changes to try all possible combinations (including the initial one), then Ivan wants to know this way.
Help Ivan by showing him the way to change parameters!
|
If $m = 1$, then everything is simple. Cycle exists if $a[1] = 2$, and path exists if $b[1] = 1$ or $b[1] = a[1]$. Let's consider the case when $m = 2$. Let's call the combination odd if the sum of parameters is odd for this combination, and even otherwise. It's easy to see that if $a[1]$ and $a[2]$ are both odd, then it's impossible to construct a cycle because the number of even combinations is greater than the number of odd combinations. Furthermore, it's impossible to construct a path if our initial combination is an odd one. Let's show how to construct answer in all other cases. Constructing a cycle is easy if at least one of $a[i]$ is even: And constructing a path can be divided into four cases. Starting point in corner: Start near the border: Both coordinates of starting point are even: Both coordinates are odd: So the case when $m = 2$ is solved. Now, if $m = 3$, then it can be reduced to $m = 2$ as follows: Suppose we have $a[1] = 3, a[2] = 3, a[3] = 3$. Then let's at first consider only combinations where the third parameter is equal to $1$: Then, if we need to add the combinations with third parameter equal to $2$, we mirror the "layer": And if we need to add the third "layer", we mirror it again: And so on. This way can also be used to reduce $m > 3$ to $m = 2$.
|
[] | 3,200
| null |
864
|
A
|
Fair Game
|
Petya and Vasya decided to play a game. They have $n$ cards ($n$ is an even number). A single integer is written on each card.
Before the game Petya will choose an integer and after that Vasya will choose another integer (\textbf{different} from the number that Petya chose). During the game each player takes all the cards with number he chose. For example, if Petya chose number $5$ before the game he will take all cards on which $5$ is written and if Vasya chose number $10$ before the game he will take all cards on which $10$ is written.
The game is considered fair if Petya and Vasya can take all $n$ cards, and the number of cards each player gets is the same.
Determine whether Petya and Vasya can choose integer numbers before the game so that the game is fair.
|
This problem has many different solutions. Let's consider one of them. At first sort all numbers in non-descending order. Then the first $n / 2$ numbers must be equal to each other, the following $n / 2$ numbers must be equal to each other, and the number from the first half must be different from the number from the second half. So, if all conditions: $a[1] = a[n / 2]$ $a[n / 2 + 1] = a[n]$ $a[1] \neq a[n]$ are met after sorting, the answer is <<YES>>. Vasya must choose before the game number $a[1]$ and Petya - $a[n]$ (or vice versa). If at least one from the described conditions is failed, the answer is <<NO>>.
|
[
"implementation",
"sortings"
] | 1,000
| null |
864
|
B
|
Polycarp and Letters
|
Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string $s$ consisting only of lowercase and uppercase Latin letters.
Let $A$ be a set of positions in the string. Let's call it pretty if following conditions are met:
- letters on positions from $A$ in the string are all distinct and lowercase;
- there are no uppercase letters in the string which are situated between positions from $A$ (i.e. there is no such $j$ that $s[j]$ is an uppercase letter, and $a_{1} < j < a_{2}$ for some $a_{1}$ and $a_{2}$ from $A$).
Write a program that will determine the maximum number of elements in a pretty set of positions.
|
Let's solve the given problem in the following way. We will iterate through the letters in the string in order from left to right. If we are in position $pos$ and the next letter is uppercase we skip it. In the other case, we need to create $set$ and put letter $s_{pos}$ in it. After that we iterate through string to the right until we do not met uppercase letter or until the string does not ended. We put in $set$ each new lowercase letter. After we met uppercase letter (let position of this letter is $p$), or string is ended, we update the answer with the number of elements in $set$, and repeat described algorithm starting from position $p$.
|
[
"brute force",
"implementation",
"strings"
] | 1,000
| null |
864
|
C
|
Bus
|
A bus moves along the coordinate line $Ox$ from the point $x = 0$ to the point $x = a$. After starting from the point $x = 0$, it reaches the point $x = a$, immediately turns back and then moves to the point $x = 0$. After returning to the point $x = 0$ it immediately goes back to the point $x = a$ and so on. Thus, the bus moves from $x = 0$ to $x = a$ and back. Moving from the point $x = 0$ to $x = a$ or from the point $x = a$ to $x = 0$ is called a bus journey. In total, the bus must make $k$ journeys.
The petrol tank of the bus can hold $b$ liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.
There is a gas station in point $x = f$. This point is between points $x = 0$ and $x = a$. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain $b$ liters of gasoline.
What is the minimum number of times the bus needs to refuel at the point $x = f$ to make $k$ journeys? The first journey starts in the point $x = 0$.
|
If the bus can not reach the first gas station (i.e. $b < f$) print -1. In the other case, the bus will reach the first gas station with $b - f$ liters in the gasoline tank. Then we need to iterate through journeys from $1$ to $k$ and calculate a value $need$ - how many liters of the gasoline needed to bus reach the next gas station. If $need$ more than $b$ - print -1, because it means that the bus can not reach the next gas station even with full gasoline tank. If $need$ more than current level of gasoline in the tank the bus needs to refuel. In the other case, refuel is not necessary. After described operations we need to move to the point of next gas station and recalculate the fuel level in the tank.
|
[
"greedy",
"implementation",
"math"
] | 1,500
| null |
864
|
D
|
Make a Permutation!
|
Ivan has an array consisting of $n$ elements. Each of the elements is an integer from $1$ to $n$.
Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from $1$ to $n$ was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.
Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.
In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal — compare the second, and so on. If we have two permutations $x$ and $y$, then $x$ is lexicographically smaller if $x_{i} < y_{i}$, where $i$ is the first index in which the permutations $x$ and $y$ differ.
Determine the array Ivan will obtain after performing all the changes.
|
We will use an array $cnt$ where we will store how many times the numbers from $1$ to $n$ met in the given array $a$. Put all numbers that never occur in the array $a$ in a vector $need$ - we must add this numbers in the array $a$ to make a permutation. We will add numbers from $need$ in ascending order because we want to get lexicographically minimal permutation. Let $pos$ is a pointer on the current number $need_{pos}$ which we need to add on the current move. Initially, $pos = 0$. We will iterate through the array $a$. Let the current number equals to $a_{i}$. If $cnt_{ai} = 1$, we move to the next number in the array. If we added not all numbers from $need$, and $a_{i} > need_{pos}$ or there already was $a_{i}$ on the prefix of the array (to check it we can use, for example, boolean array), then we put $need_{pos}$ in the current position, decrease $cnt_{ai}$ on one, increase $pos$ and answer on one. If we do not change anything on that step we mark that $a_{i}$ already was on the prefix of the array. After that we move to the next number in array $a$.
|
[
"greedy",
"implementation",
"math"
] | 1,500
| null |
864
|
E
|
Fire
|
Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take $t_{i}$ seconds to save $i$-th item. In addition, for each item, he estimated the value of $d_{i}$ — the moment after which the item $i$ will be completely burned and will no longer be valuable for him at all. In particular, if $t_{i} ≥ d_{i}$, then $i$-th item cannot be saved.
Given the values $p_{i}$ for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item $a$ first, and then item $b$, then the item $a$ will be saved in $t_{a}$ seconds, and the item $b$ — in $t_{a} + t_{b}$ seconds after fire started.
|
If Polycarp will save two items, it is more profitable to first save the one whose $d$ parameter is less. So, you can sort items by the parameter $d$. Let $dp_{i, j}$ be the maximum total value of items Polycarp can save by checking first $i - 1$ items in $j$ seconds. Here are two types of transitions. Polycarp can either save current item or skip it: $dp_{i + 1, j + ti} = max(dp_{i + 1, j + ti}, dp_{i, j} + p_{i})$, if $j + t_{i} < d_{i}$ $dp_{i + 1, j} = max(dp_{i + 1, j}, dp_{i, j})$ To restore the sequence of items Polycarp can save you can remember for each pair ($i, j$) whether you took a thing with the number $i - 1$ when updating the value $dp_{i, j}$. Overall complexity: $O(n \cdot max_{1 \le i \le n}d_{i})$.
|
[
"dp",
"sortings"
] | 2,000
| null |
864
|
F
|
Cities Excursions
|
There are $n$ cities in Berland. Some pairs of them are connected with $m$ directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities $(x, y)$ there is at most one road from $x$ to $y$.
A path from city $s$ to city $t$ is a sequence of cities $p_{1}$, $p_{2}$, ... , $p_{k}$, where $p_{1} = s$, $p_{k} = t$, and there is a road from city $p_{i}$ to city $p_{i + 1}$ for each $i$ from $1$ to $k - 1$. The path can pass multiple times through each city except $t$. It can't pass through $t$ more than once.
A path $p$ from $s$ to $t$ is ideal if it is the lexicographically minimal such path. In other words, $p$ is ideal path from $s$ to $t$ if for any other path $q$ from $s$ to $t$ $p_{i} < q_{i}$, where $i$ is the minimum integer such that $p_{i} ≠ q_{i}$.
There is a tourist agency in the country that offers $q$ unusual excursions: the $j$-th excursion starts at city $s_{j}$ and ends in city $t_{j}$.
For each pair $s_{j}$, $t_{j}$ help the agency to study the ideal path from $s_{j}$ to $t_{j}$. Note that it is possible that there is no ideal path from $s_{j}$ to $t_{j}$. This is possible due to two reasons:
- there is no path from $s_{j}$ to $t_{j}$;
- there are paths from $s_{j}$ to $t_{j}$, but for every such path $p$ there is another path $q$ from $s_{j}$ to $t_{j}$, such that $p_{i} > q_{i}$, where $i$ is the minimum integer for which $p_{i} ≠ q_{i}$.
The agency would like to know for the ideal path from $s_{j}$ to $t_{j}$ the $k_{j}$-th city in that path (on the way from $s_{j}$ to $t_{j}$).
For each triple $s_{j}$, $t_{j}$, $k_{j}$ ($1 ≤ j ≤ q$) find if there is an ideal path from $s_{j}$ to $t_{j}$ and print the $k_{j}$-th city in that path, if there is any.
|
There is a direct graph. For each query, you need to find the $k_{j}$-th vertex in the lexicographically minimal path from $s_{j}$ to $t_{j}$. First group the queries on the vertex $t_{j}$ and find all vertices from which the vertex $t_{j}$ is achievable. For this you can invert all the arcs and run dfs from the vertex $t_{j}$. Now consider the query ($s_{j}$, $t_{j}$). For this query, you need to find the lexicographically minimal path from $s_{j}$ to $t_{j}$. If the vertex $t_{j}$ is not achievable from $s_{j}$, then the answer is '-1'. Otherwise, in the lexicographically minimal path $p$ from $s_{j}$ to $t_{j}$ the vertex $p_{i}$ ($i > 1$) is the minimal vertex from vertices $u$ such that there exists an arc ($p_{i - 1}, u$) and $t_{j}$ is achievable from $u$. Thus, we can build a new graph consisting of arcs satisfying the previous condition. Let us invert the arcs in this graph. Consider the vertices achievable from $t_{j}$ in this graph. They form an outgoing tree. Only for these vertices there is a lexicographically minimal path to $t_{j}$. The lexicographically minimal path from the vertex $s_{j}$ to the vertex $t_{j}$ is equal to the inverted path from $t_{j}$ to $s_{j}$ in this tree. So, we can use binary climb to get the $k$-th vertex on this path.
|
[
"dfs and similar",
"graphs",
"trees"
] | 2,700
| null |
865
|
A
|
Save the problem!
|
Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.
People don't use cash as often as they used to. Having a credit card solves some of the hassles of cash, such as having to receive change when you can't form the exact amount of money needed to purchase an item. Typically cashiers will give you as few coins as possible in change, but they don't have to. For example, if your change is 30 cents, a cashier could give you a 5 cent piece and a 25 cent piece, or they could give you three 10 cent pieces, or ten 1 cent pieces, two 5 cent pieces, and one 10 cent piece. Altogether there are 18 different ways to make 30 cents using only 1 cent pieces, 5 cent pieces, 10 cent pieces, and 25 cent pieces. Two ways are considered different if they contain a different number of at least one type of coin. Given the denominations of the coins and an amount of change to be made, how many different ways are there to make change?
As we mentioned before, we lost all the test cases for this problem, so we're actually going to give you the number of ways, and want you to produce a test case for which the number of ways is the given number. There could be many ways to achieve this (we guarantee there's always at least one), so you can print any, as long as it meets the constraints described below.
|
The simplest solution is to make the denominations always ${1, 2}$, and set $N = 2 \cdot A - 1$. This provides exactly $A$ ways to make change, because you can choose any number of 2 cent pieces from $0$ to $A - 1$, then the rest must be 1 cent pieces.
|
[
"constructive algorithms"
] | 1,400
| null |
865
|
B
|
Ordering Pizza
|
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly $S$ slices.
It is known that the $i$-th contestant will eat $s_{i}$ slices of pizza, and gain $a_{i}$ happiness for each slice of type 1 pizza they eat, and $b_{i}$ happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?
|
To simplify things, let's first add a dummy contestant who will eat all the "leftover" pizza but gain no happiness. Then let's sort the contestants by $b_{i} - a_{i}$. Now we can describe the optimal way to feed the contestants once the pizzas are already bought: we should line up the contestants in order, and line up the pizzas in order with the type 1 pizzas at the front and type 2 pizzas at the back. Then the first contestant should take the first $s_{1}$ slices, then the second contestant should take the next $s_{2}$ slices, and so on. Observe that there can be at most 1 pizza whose slices are taken by some contestants prefer type 1 and others prefer type 2. The remainder of pizzas will have only one type of preference (or possibly no preference), so those pizzas can be made of whichever type is preferred. For the final pizza we can check both possibilities and order the one that provides more happiness.
|
[
"binary search",
"sortings",
"ternary search"
] | 1,900
| null |
865
|
C
|
Gotta Go Fast
|
You're trying to set the record on your favorite video game. The game consists of $N$ levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the $i$-th level in either $F_{i}$ seconds or $S_{i}$ seconds, where $F_{i} < S_{i}$, and there's a $P_{i}$ percent chance of completing it in $F_{i}$ seconds. After completing a level, you may decide to either continue the game and play the next level, or reset the game and start again from the first level. Both the decision and the action are instant.
Your goal is to complete all the levels sequentially in at most $R$ total seconds. You want to minimize the expected amount of time playing before achieving that goal. If you continue and reset optimally, how much total time can you expect to spend playing?
|
Let's change the game by adding a deterministic variant, which takes exactly $K$ seconds to complete. Initially, you play the original (random) game, but between levels (including before the first level), you're allowed to switch to the deterministic game (instead of restarting). You finish when you either complete the original game in at most $R$ seconds, or complete the deterministic game. This modified version is easier to analyze because there are no loops in the state graph. We can compute the optimal strategy by starting from the end and working backwards. For each level, and each amount of time it could have taken to reach this level, we can compute the expected time to completion for each of the 2 actions we can take, then perform whichever action is lower. Eventually we'll work our way back to the beginning of the game. If the optimal strategy is to immediately switch to the deterministic game, then the answer is greater than $K$. Otherwise it's less than $K$. This allows us to binary search the answer.
|
[
"binary search",
"dp"
] | 2,400
| null |
865
|
D
|
Buy Low Sell High
|
You can perfectly predict the price of a certain stock for the next $N$ days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the $N$ days you would like to again own zero shares, but want to have as much money as possible.
|
Let's introduce the idea of options to the problem. Instead of having to buy stock when it is at a given price, each day you gain the option to buy a share at that days price, which you can exercise at any time in the future. This way we only need to exercise an option in order to sell it, and we never need to "hold" any stock. Each day, 2 things happen. First, we get one more option. Second, if there is some option whose price is lower than today's price, we can be sure that we're going to exercise that option. What we don't know is when it's best to sell that option. However, we don't need to know when the best time is to sell - we can just sell it now, but give ourselves the option to buy it back at the price we just sold it for. Options can be stored in a heap since we only ever care about the cheapest one. Running time $O(N\log N)$.
|
[
"constructive algorithms",
"data structures",
"greedy"
] | 2,400
| null |
865
|
E
|
Hex Dyslexia
|
Copying large hexadecimal (base 16) strings by hand can be error prone, but that doesn't stop people from doing it. You've discovered a bug in the code that was likely caused by someone making a mistake when copying such a string. You suspect that whoever copied the string did not change any of the digits in the string, nor the length of the string, but may have permuted the digits arbitrarily. For example, if the original string was $0abc$ they may have changed it to $a0cb$ or $0bca$, but not $abc$ or $0abb$.
Unfortunately you don't have access to the original string nor the copied string, but you do know the length of the strings and their numerical absolute difference. You will be given this difference as a hexadecimal string $S$, which has been zero-extended to be equal in length to the original and copied strings. Determine the smallest possible numerical value of the original string.
|
First, observe that for a solution to exist, the sum of the digits in the input must be divisible by 15. This is because of the Casting out Nines rule, but applied in base 16. Furthermore, the sum of digits, when divided by 15, tells us how many carries must be performed when adding the answer to the input. We can try every possible set of positions for the carries, of which there are at most $\textstyle{\binom{13}{6}}=1716$ ways. Once the carries are fixed, for each position we know the exact difference between the original digit in that position and the permuted digit in that position. Now let's consider the permutation itself. Any permutation can be decomposed into cycles. Because we're looking for the minimum solution, it must be the case that every cycle in the permutation contains a zero. If there were a cycle without a zero, we could reduce every number in the cycle by the minimum value and produce a smaller solution. Furthermore, because every cycle contains a common element, that means the permutation can be written as a single cycle, since two cycles with a common element can be merged into one cycle using that element. To build such a cycle, we can start at a zero, and when we add a digit to the path we know based on its position what the difference must be between it and the previous digit. For each of the $2^{|S|}$ subsets of positions we can compute the minimum value that corresponds to a path through those positions. This step is $O(|S| \cdot 2^{|S|})$. Side note: the answer, if it exists, always begins with 0. There are 2 cases to consider. If $S$ begins with an 'f', then the only possible solutions begin with a 0. Otherwise, the value given by $\frac{\mathrm{S}}{\mathrm{L}5}$ is a valid solution, and starts with 0.
|
[
"bitmasks",
"brute force",
"dp",
"graphs"
] | 3,300
| null |
865
|
F
|
Egg Roulette
|
The game of Egg Roulette is played between two players. Initially $2R$ raw eggs and $2C$ cooked eggs are placed randomly into a carton. The shells are left on so there is no way to distinguish a raw egg from a cooked egg. One at a time, a player will select an egg, and then smash the egg on his/her forehead. If the egg was cooked, not much happens, but if the egg was raw, it will make quite the mess. This continues until one player has broken $R$ raw eggs, at which point that player is declared the loser and the other player wins.
The order in which players take turns can be described as a string of 'A' and 'B' characters, where the $i$-th character tells which player should choose the $i$-th egg. Traditionally, players take turns going one after the other. That is, they follow the ordering "ABABAB...". This isn't very fair though, because the second player will win more often than the first. We'd like you to find a better ordering for the players to take their turns. Let's define the unfairness of an ordering as the absolute difference between the first player's win probability and the second player's win probability. We're interested in orderings that minimize the unfairness. We only consider an ordering valid if it contains the same number of 'A's as 'B's.
You will also be given a string $S$ of length $2(R + C)$ containing only 'A', 'B', and '?' characters. An ordering is said to match $S$ if it only differs from $S$ in positions where $S$ contains a '?'. Of the valid orderings that minimize unfairness, how many match $S$?
|
We can permute any prefix of an ordering containing at most $R - 1$ 'A's or $R - 1$ 'B's without changing the unfairness. This is because within that prefix one of the players cannot lose the game. This means that every ordering there is a unique ordering with the same unfairness that begins with exactly $R - 1$ 'A's followed by $R - 1$ 'B's and can be obtained by permuting such a prefix. Let's call this the canonical form of an ordering. To search for canonical forms, we need to consider the remaining $2 * (C + 1)$ turns. The constraints set this to at most 42, so we can split it into two halves, compute every possible ordering for the left $C + 1$ turns and right $C + 1$ turns, then use a meet-in-the-middle algorithm to find those that minimize unfairness. For each ordering in each half, we also need to compute how many corresponding orderings match the given string $S$. For the right half this is easy - every ordering either matches once or not at all. For the left half we have to consider non-canonical orderings. To compute this, we first need to find the longest prefix of the ordering that can be permuted. This is the longest prefix where every turn is the same as the first turn. Then we need to count how many 'A' and 'B' characters are in the ordering within that prefix, and how many 'A' and 'B' characters are in $S$ within that prefix. If there are more 'A' or 'B' characters in $S$ than the ordering, there are zero matches, otherwise the number of matches is given by a binomial coefficient. The total runtime is $O(C * 2^{C})$.
|
[
"bitmasks",
"brute force",
"divide and conquer",
"math",
"meet-in-the-middle"
] | 3,300
| null |
865
|
G
|
Flowers and Chocolate
|
It's Piegirl's birthday soon, and Pieguy has decided to buy her a bouquet of flowers and a basket of chocolates.
The flower shop has $F$ different types of flowers available. The $i$-th type of flower always has exactly $p_{i}$ petals. Pieguy has decided to buy a bouquet consisting of exactly $N$ flowers. He may buy the same type of flower multiple times. The $N$ flowers are then arranged into a bouquet. The position of the flowers within a bouquet matters. You can think of a bouquet as an ordered list of flower types.
The chocolate shop sells chocolates in boxes. There are $B$ different types of boxes available. The $i$-th type of box contains $c_{i}$ pieces of chocolate. Pieguy can buy any number of boxes, and can buy the same type of box multiple times. He will then place these boxes into a basket. The position of the boxes within the basket matters. You can think of the basket as an ordered list of box types.
Pieguy knows that Piegirl likes to pluck a petal from a flower before eating each piece of chocolate. He would like to ensure that she eats the last piece of chocolate from the last box just after plucking the last petal from the last flower. That is, the total number of petals on all the flowers in the bouquet should equal the total number of pieces of chocolate in all the boxes in the basket.
How many different bouquet+basket combinations can Pieguy buy? The answer may be very large, so compute it modulo $1000000007 = 10^{9} + 7$.
|
Let's first consider how to compute the number of ways to make a bouquet with exactly $K$ petals. Define a polynomial $P(x)=\sum_{i=1}^{F}x^{p}$. Then if we compute $P(x)^{N}$, the coefficient of $x^{K}$ gives the number of ways to make a bouquet with exactly $K$ petals. This is because each possible bouquet produces a term with an exponent equal to its number of petals. Now lets consider how to compute the number of ways to make a basket with exactly $K$ chocolates. Define a polynomial $Q(x)=1-\sum_{i=1}^{B}x^{c},$. Then if we compute $x^{-K}({\mathrm{mod}}Q(x))$, the coefficient of $x^{0}$ gives the number of ways to make a basket with exactly $K$ chocolates. This can be derived from a Generating Function, but we will provide an alternate derivation. Consider the following algorithm for computing the number of ways to make a basket with $K$ chocolates: The final answer is the sum, over all values of $K$, of the number of bouquets with $K$ petals times the number of baskets with $K$ chocolates. The number of bouquets is given by the $x^{K}$ coefficient of $P(x)^{N}$, or equivalently, the $x^{ - K}$ coefficient of $P(x^{ - 1})^{N}$, and the number of baskets is given by the coefficient of $x^{0}$ of $x^{-K}({\mathrm{mod}}Q(x))$. It follows that the answer is simply the coefficient of $x^{0}$ of $P(x^{-1})^{N}(\mathrm{mod}Q(x))$. This can be computed using $O(\log N+\sum\log p_{i})$ polynomial multiplications, each of which takes $O(max(c_{i})^{2})$ time, using naive multiplication, for a total runtime of $O((\log N+\sum\log p_{i})\cdot m a x(c_{i})^{2})$.
|
[
"combinatorics",
"math",
"matrices"
] | 3,300
| null |
867
|
A
|
Between the Offices
|
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last $n$ days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last $n$ days, or not.
|
The answer is "YES" if the first character of the given string is 'S' and the last character is 'F', otherwise it's "NO".
|
[
"implementation"
] | 800
| null |
868
|
A
|
Bark to Unlock
|
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.
Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark $n$ distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.
|
If the answer is 'yes', then the password is either one of the given strings, or can be formed by taking the last letter and the first letter of some of the given strings (these strings can be the same). This can be checked straightforwardly in $O(n^{2})$ time.
|
[
"brute force",
"implementation",
"strings"
] | 900
| null |
868
|
B
|
Race Against Time
|
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other.
The entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time $h$ hours, $m$ minutes, $s$ seconds.
Last time Misha talked with the coordinator at $t_{1}$ o'clock, so now he stands on the number $t_{1}$ on the clock face. The contest should be ready by $t_{2}$ o'clock. In the terms of paradox it means that Misha has to go to number $t_{2}$ somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction.
Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way).
Given the hands' positions, $t_{1}$, and $t_{2}$, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from $t_{1}$ to $t_{2}$ by the clock face.
|
There are $12 \times 60 \times 60$ positions on the clock face that can be occupied by hands and start/finish positions. After marking the positions occupied by hands, we can straightforwardly try both directions of moving and check if we arrive to the finish without encountering any of the hands. Of course, there are many solutions that are more efficient.
|
[
"implementation"
] | 1,400
| null |
868
|
C
|
Qualification Rounds
|
Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of $n$ problems, and they want to select any non-empty subset of it as a problemset.
$k$ experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.
Determine if Snark and Philip can make an interesting problemset!
|
Let us show that if a solution exists, then there is always a solution that uses at most two problems. First, if there is a problem not known to any of the teams, that we can just take this only problem in the set. Next, suppose that there is a problem known only to one of the teams. If there is a problem this team doesn't know, then these two problems make a good set. Otherwise, the team knows all the problems, hence we cannot find a good set. In the rest case, each problem is known to at least two of the teams. Now, if there is a good set of problems, then each of the problems in the set must be known to exactly two of the teams. Indeed, let $p_{i}$ be the number of teams that knows the problem. If a good set contains $k$ problems, then we must have $\textstyle\sum p_{i}\leq2k$, since otherwise we would have a team that knows more than half of the problems by pigeonhole principle. We also have $p_{i} \ge 2$, hence $\textstyle\sum p_{i}\geq2k$, and only the case $p_{i} = 2$ is possible. At this point, if we can find a pair of problems with $p_{i} = 2$ and non-intersecting set of teams, then we are done. Otherwise, we can show that a good set does not exist by case analysis. To avoid $O(n^{2})$ solution, we can leave at most $2^{4}$ problems with unique types (sets of teams) and do pairwise checking on them. This solution has $O(n)$ complexity.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"dp"
] | 1,500
| null |
868
|
D
|
Huge Strings
|
You are given $n$ strings $s_{1}, s_{2}, ..., s_{n}$ consisting of characters $0$ and $1$. $m$ operations are performed, on each of them you concatenate two existing strings into a new one. On the $i$-th operation the concatenation $s_{ai}s_{bi}$ is saved into a new string $s_{n + i}$ (the operations are numbered starting from $1$). After each operation you need to find the maximum positive integer $k$ such that all possible strings consisting of $0$ and $1$ of length $k$ (there are $2^{k}$ such strings) are substrings of the new string. If there is no such $k$, print $0$.
|
The key insight is that despite the strings can get very long, the answer for each string at most 9. Indeed, let us keep track of the number of distinct substrings of length 10 across all strings. Obviously, this number is at most 100 for the initial strings. Once we obtain a new string as a concatenation of two old ones, the only new substrings can arise on the border of these two strings, and there can be at most 9 of these substrings. Since $100 + 100 \cdot 9 < 2^{10}$, it is impossible to construct a string with answer 10. Now, the solution is for each new string store the set of all distinct substrings of length at most 9. In order to construct this set for subsequent strings, we will have to store the first and the last 9 characters of each string (probably less if the string is shorter than 9). The number of operations is roughly $100 \cdot 2^{10}$ if we store the distinct substrings in arrays, but can be made smaller if we use bitsets.
|
[
"bitmasks",
"brute force",
"dp",
"implementation",
"strings"
] | 2,200
| null |
868
|
E
|
Policeman and a Tree
|
You are given a tree (a connected non-oriented graph without cycles) with vertices numbered from $1$ to $n$, and the length of the $i$-th edge is $w_{i}$. In the vertex $s$ there is a policeman, in the vertices $x_{1}, x_{2}, ..., x_{m}$ ($x_{j} ≠ s$) $m$ criminals are located.
The policeman can walk along the edges with speed $1$, the criminals can move with arbitrary large speed. If a criminal at some moment is at the same point as the policeman, he instantly gets caught by the policeman. Determine the time needed for the policeman to catch all criminals, assuming everybody behaves optimally (i.e. the criminals maximize that time, the policeman minimizes that time). Everybody knows positions of everybody else at any moment of time.
|
Suppose that the policeman is moving from $v$ to $u$ via the tree edge. The criminals can now assume any positions in two halves of the tree (but cannot travel from one half to another). Let $dp_{e, k, a}$ be the resulting time to catch the criminals if the policeman have just started to travel along a (directed) edge $e$, there are $k$ criminals in total, and $a$ of them are in the half tree "in front" of the policeman. If the edge $e$ leads into a leaf of the tree, then the policeman catches everyone in this leaf, and his next step is to go back using the same edge. Otherwise, the criminals must have distributed optimally in the subtrees starting with edges $e_{1}, ..., e_{j}$. The policeman cannot win within time $T$ if there is a distribution $a_{1}, ..., a_{j}$ with $\textstyle\sum a_{i}=a$ such that $dp_{ei, k, ai} > T$ for every $i$. The optimal value of $T$ can be found with binary search: for a particular $T$ find the smallest $a_{i}$ such that $dp_{ei, k, ai} > T$, and check if $\sum a_{i}\leq a$. If this is the case, the criminals can distribute so that it will take $> T$ time to catch them. The total complexity of this solution is $O(n^{2}m^{2}\log A)$, since we have $O(nm^{2})$ DP states, with each state having $O(n)$ transitions, and the last factor corresponding to binary search on the answer (assuming the answer is at most $A$).
|
[
"dp",
"graphs",
"trees"
] | 2,700
| null |
868
|
F
|
Yet Another Minimization Problem
|
You are given an array of $n$ integers $a_{1}... a_{n}$. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into $k$ non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.
|
First, let us solve the problem in $O(kn^{2})$ time with a simple DP. Let $dp_{i, j}$ be the smallest cost of a partition of first $j$ elements into $i$ parts. Clearly, $dp_{i, j} = min_{j' < j}dp_{i - 1, j'} + cost(j', j)$. We can optimize the cost computation by moving $j'$ from right to left and maintaining frequency for each element, since by introducing an element $x$ into the segment, we increase the cost by $f_{x}$ - the number of occurences of $x$. To optimize this further, let us note that $p(j)$ - the (leftmost) optimal value of $j'$ for a particular $j$ is monotonous in $j$ on any step $i$. Indeed, suppose that $j_{1} < j_{2}$, and $dp_{i - 1, x} + cost(x, j_{2}) < dp_{i - 1, p(j1)} + cost(p(j_{1}), j_{2})$ for $x < p(j_{1})$. But $cost(x, j_{2}) - cost(p(j_{1}), j_{2}) \ge cost(x, j_{1}) - cost(p(j_{1}), j_{1})$, since introducing an element into a segment $[l, j_{2}]$ is at least as costly as introducing it into a segment $[l, j_{1}]$. Finally, $dp_{i - 1, p(j1)} - dp_{i - 1, x} > cost(x, j_{2}) - cost(p(j_{1}), j_{2}) \ge cost(x, j_{1}) - cost(p(j_{1}), j_{1})$, and $dp_{i - 1, p(j1)} + cost(p(j_{1}), j_{1}) > dp_{i - 1, x} + cost(x, j_{1})$, which contradicts the optimality of $p(j_{1})$. We can now apply the "divide-and-conquer" DP optimization: suppose that for a segment $[l, r]$ we know that $p(j)\in[L,R]$ for each $j\in[L,r]$. Choose $m$ as the midpoint of $[l, r]$ and find $p(m)$ by explicitly trying all values in $[L, R]$. We now proceed recursively into segments $[l, m - 1]$ with $p(j)\in[L,M]$, and $[m + 1, r]$ with $p(j)\in[M,R]$. Assuming unit cost for $cost(l, r)$ computation, one can show that the computation of all values of $dp_{i, j}$ for a particular $i$ takes $O(n\log n)$ time. The final detail is that the time needed to compute $cost(l, r)$ can be made amortized constant (that is, $O(n\log n)$ in total per layer) if we store the value $cost(p(m), m)$ from the parent segment, and add/remove segment elements one by one to obtain all subsequent values. The total complexity is now $O(k n\log n)$.
|
[
"divide and conquer",
"dp"
] | 2,500
| null |
868
|
G
|
El Toll Caves
|
The prehistoric caves of El Toll are located in Moià (Barcelona). You have heard that there is a treasure hidden in one of $n$ possible spots in the caves. You assume that each of the spots has probability $1 / n$ to contain a treasure.
You cannot get into the caves yourself, so you have constructed a robot that can search the caves for treasure. Each day you can instruct the robot to visit exactly $k$ distinct spots in the caves. If none of these spots contain treasure, then the robot will obviously return with empty hands. However, the caves are dark, and the robot may miss the treasure even when visiting the right spot. Formally, if one of the visited spots does contain a treasure, the robot will obtain it with probability $1 / 2$, otherwise it will return empty. Each time the robot searches the spot with the treasure, his success probability is independent of all previous tries (that is, the probability to miss the treasure after searching the right spot $x$ times is $1 / 2^{x}$).
What is the expected number of days it will take to obtain the treasure if you choose optimal scheduling for the robot? Output the answer as a rational number modulo $10^{9} + 7$. Formally, let the answer be an irreducible fraction $P / Q$, then you have to output $P\cdot Q^{-1}\operatorname{mod}\left(10^{9}+7\right)$. It is guaranteed that $Q$ is not divisible by $10^{9} + 7$.
|
Let $a_{i, j}$ be the number of times we have checked spot $j$ after $i$ days. Assuming that the spot $j$ contains the treasure, we can see that the expected number of days to find the treasure is $\textstyle\sum_{i=0}^{\infty}2^{-a_{i,j}}$. Hence the unconditional expectation of the answer is ${\frac{1}{n}}\sum_{i=0}^{\infty}\sum_{j=0}^{n-1}2^{-a_{i,j}}$. This formula implies that the optimal strategy is to keep the visiting frequencies for all spots as close as possible, since the sum $\textstyle\sum_{j=0}^{n-1}2^{-n_{i,j}}$ is minimized under $\textstyle{\sum_{j=0}^{n-1}a_{i,j}=i k}$ when $a_{i, j}$ is the smoothest partition of $ik$. One implementation of this strategy is to visit spots $i k\ {\mathrm{mod}}\ n,(i k+1)\ {\mathrm{mod}}\ n,\ldots,(i k+k-1)\ {\mathrm{mod}}\ n$ on day $i$. Note further that this strategy always visits spots in batches of size $\operatorname*{gcd}(n,k)$, hence we can divide both $n$ and $k$ by their GCD. Let us now consider an example of $n = 8$, $k = 3$. Let $E_{i}$ be the expected number of days to find the treasure in spot $i$ according to the optimal strategy above. We can see that $E_{3} = E_{0} + 1$, $E_{4} = E_{1} + 1$, $...$, $E_{7} = E_{4} + 1$, because a cell $j + k$ is visited on day $i$ iff the cell $j$ was visited on day $i - 1$. We also have $E_{0} = E_{5} / 2 + 1$ for the same reason except for that the cell $0$ was visited on the first day. This argument allows to express, say, $E_{0}$ as a linear expression of itself, and find the answer in $O(n)$ time. Another approach is to substitute the expressions until we cross the end of the sequence once: $E_{0} = E_{3} - 1 = E_{6} - 2 = 2E_{1} - 4$, also $E_{1} = 2E_{2} - 4$, but $E_{2} = E_{5} - 1 = 2E_{0} - 3$. We have obtained a similar set of linear relations of three spots with difference 2. To reduce to $n = 3$, $k = 2$ let us group $E_{j}$ by $j~{\mathrm{mod}}~k$: $E_{0} + E_{3} + E_{6} = 3E_{0} + 3$, $E_{1} + E_{4} + E_{7} = 3E_{1} + 3$, $E_{2} + E_{5} = 2E_{2} + 1$. We can see that the total contribution of all $E_{j}$ for $j\equiv x{\mathrm{~(mod~}}k\right)$ is a linear function in $E_{x}$, with coefficients depending on whether $x<\eta\operatorname{Inlol}k$. The main idea is that we continue this process with a different set of linear equations, effectively obtaining Euclid's algorithm that stores some additional data. Let us now describe the general solution. Assume that we have a set of variables $X_{0}, ..., X_{n - 1}$ satisfying $X_{i + k} = A(X_{i})$ for $i + k < n$, and $X_{i + k - n} = B(X_{i})$ for $i + k \ge n$. Assume further that the answer $E=\sum_{j=0}^{k-1}S_{1}(X_{j})+\sum_{j=k}^{n-1}S_{2}(X_{j})$. Let $k^{\prime}=n{\mathrm{~mod~}}k$. For $j < k'$, by applying relations $A$ and $B$ successively we obtain $X_{j+k-k^{\prime}}=B(A^{[n/k]}(X_{j}))$, hence $X_{j+k^{\prime}-k}=A^{-\left[n/k\right]}(B^{-1}(X_{j}))$ for $j + k' \ge k$. Similarly, $X_{j+k^{\prime}}=A^{-\,[n/k-1]}(B^{-1}(X_{j}))$ for $j + k' < k$. Also, $E=\sum_{j=0}^{k^{\prime}-1}S_{1}^{\prime}(X_{j})+\sum_{j=k^{\prime}}^{k-1}S_{2}^{\prime}(X_{j})$, where $S_{1}^{\prime}=S_{1}+\sum_{t=1}^{[n/k]}S_{2}(A^{t})$, $S_{2}^{\prime}=S_{1}+\sum_{t=1}^{\left\lfloor{n}/{k}-1\right\rfloor}S_{2}({A^{t}})$. It follows that the transformation $n \rightarrow k$, $k \rightarrow k'$, $A\to A^{-\left[n/k-1\right]}(B^{-1}(X_{j}))$, $B\rightarrow A^{-\,[n/k]}(B^{-\,1}(X_{j}))$, $S_{1} \rightarrow S'_{1}$, $S_{2} \rightarrow S'_{2}$ produces the same answer $E$. In the end of this process we have $n = 1$, $k = 0$, hence we have a linear equation $X_{0} = A(X_{0})$. After finding $X_{0}$, the answer is $S_{2}(X_{0})$. The number of reductions of the above type is $O(\log n)$, with each transformation possible to do in $O(\log(n/k))$ time, ($S_{1} \rightarrow S'_{1}$ and $S_{2} \rightarrow S'_{2}$ require fast matrix exponentation). The total number of operations is $O(\log n)$ per test.
|
[
"math"
] | 3,300
| null |
869
|
A
|
The Artful Expedient
|
Rock... Paper!
After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.
A positive integer $n$ is decided first. Both Koyomi and Karen independently choose $n$ distinct positive integers, denoted by $x_{1}, x_{2}, ..., x_{n}$ and $y_{1}, y_{2}, ..., y_{n}$ respectively. They reveal their sequences, and repeat until \textbf{all of $2n$ integers become distinct}, which is the only final state to be kept and considered.
Then they count the number of ordered pairs $(i, j)$ ($1 ≤ i, j ≤ n$) such that the value $x_{i}$ xor $y_{j}$ equals to one of the $2n$ integers. Here xor means the bitwise exclusive or operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.
Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.
|
First approach: Optimize the straightforward solution. The $O(n^{3})$ solution is to iterate through $(i, j)$ pairs, then iterate over $k$ and check whether $x_{i}$ xor $y_{j}$ equals either $x_{k}$ or $y_{k}$. But it doesn't fit into the time limit. We try to get rid of the $k$ loop and make the check faster. Here's the insight: we create an array $a$, and let $a[i]$ denote "whether value $i$ appears in the given $2n$ integers". In this way we can make the check comsume $O(1)$ time (with $O(n)$ preprocessing for $a$), resulting in an $O(n^{2})$ overall time complexity. Please see the model solution for an implementation. A detail worth mentioning is that $x_{i}$ xor $y_{j}$ may exceed $2 \cdot 10^{6}$ and become as large as $2097152 = 2^{21}$. Thus the array should be of size $2097152$ instead of $2 \cdot 10^{6}$ and if not, invalid memory access may take place. Second approach: Believe in magic. Let's forget about all loops and algorithmic stuff and start fresh. What's the parity of the answer? Looking at the samples again, do note that Karen scores two consecutive wins. The fact is that, Karen always wins. Proof. For any pair $(i, j)$, if an index $k$ exists such that $x_{i}$ xor $y_{j}$ $= x_{k}$, then this $k$ is unique since all $2n$ integers are distinct. Then, pair $(k, j)$ also fulfills the requirement, since $x_{k}$ xor $y_{j}$ $= x_{i}$. The similar goes for cases where $x_{i}$ xor $y_{j}$ $= y_{k}$. Therefore, each valid pair satisfying the requirement can be mapped to exactly another valid pair, and the mapping is unique and involutory (that is, $f(f(u)) = u$). Thus, the number of such pairs is always even. So, Karen still claims her constant win. Maybe it's Koyomi's obscure reconciliation ;)
|
[
"brute force",
"implementation"
] | 1,100
|
#include <stdio.h>
int main()
{
puts("Karen");
return 0;
}
|
869
|
B
|
The Eternal Immortality
|
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every $a!$ years. Here $a!$ denotes the factorial of integer $a$, that is, $a! = 1 × 2 × ... × a$. Specifically, $0! = 1$.
Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of $b!$ years, that is, $\frac{\partial!}{\alpha!}$. Note that when $b ≥ a$ this value is always integer.
As the answer can be quite large, it would be enough for Koyomi just to know \textbf{the last digit of the answer in decimal representation}. And you're here to provide Koyomi with this knowledge.
|
Multiply instead of divide. What happens to the last digit when multiplying? $\frac{\partial!}{\alpha!}$ equals $(a + 1) \cdot (a + 2) \cdot ... \cdot (b - 1) \cdot b$. Consider the multiplicands one by one, and when the last digit of the product becomes $0$, it stays unchanged from then on. Hence we can multiply the integers one by one, only preserving the last digit (take it modulo $10$ whenever possible), and stop when it becomes $0$. It's obvious that at most $10$ multiplications are needed before stopping, and it's not hard to prove a tighter upper bound of $5$. Take care, integer overflow can emerge everywhere!
|
[
"math"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
long long L,R;
int ans;
int main()
{
scanf("%lld%lld",&L,&R);
if (R-L>=10) printf("%d\n",0);
else
{
ans=1;
for (long long i=L+1;i<=R;i++)
ans=(1LL*ans*(i%10))%10;
printf("%d\n",ans);
}
return 0;
}
|
869
|
C
|
The Intriguing Obsession
|
— This is not playing but duty as allies of justice, Nii-chan!
— Not allies but justice itself, Onii-chan!
With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands!
There are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of $a$, $b$ and $c$ distinct islands respectively.
Bridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length $1$. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is \textbf{at least $3$}, apparently in order to prevent oddities from spreading quickly inside a cluster.
The Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo $998 244 353$. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other.
|
First step: Consider what does at least 3 mean? 'The shortest distance between them is at least 3' means it can't be 1 or 2. The distance can't be 1 means that no two islands with the same colour can be straightly connected. The distance can't be 2 means that for each island, no two islands with the same colour can both be straightly connected with it. Second step: Make the graph into 3 parts. The bridges between red and blue islands have no effection with those between red and purple ones. Therefore, we can make the graph into 3 parts: one between red and blue, one between blue and purple, and the last one between red and purple. Suppose there are $A$ red islands and $B$ blue islands, and there are $k$ bridges between them. Then, the answer will be $\textstyle{\binom{A}{k}}{\binom{B}{k}}(k!)$. So, the answer of bridges between red and blue ones should be $\sum_{k=0}^{\operatorname*{min}(A,B)}\left({\begin{array}{l}{A}\\ {k}\end{array}}\right)\left(k!\right)$ Therefore, the final answer should be $ans1 * ans2 * ans3$. You can calculate it with an $O(n^{2})$ brute force. Also, you can make it into $O(n)$.
|
[
"combinatorics",
"dp",
"math"
] | 1,800
|
#include <bits/stdc++.h>
#define Maxn 5007
#define modp 998244353
int p[Maxn][Maxn];
int pre[Maxn];
int a,b,c;
int solve(int x,int y)
{
int res=0;
for (int k=0;k<=x&&k<=y;k++)
{
int del=pre[k];
del=(1LL*del*p[x][k])%modp;
del=(1LL*del*p[y][k])%modp;
res=(res+del)%modp;
}
return res;
}
int main()
{
scanf("%d%d%d",&a,&b,&c);
memset(p,0,sizeof(p));
p[0][0]=1;
for (int i=1;i<=5000;i++)
{
p[i][0]=1;
for (int j=1;j<=i;j++)
p[i][j]=(p[i-1][j-1]+p[i-1][j])%modp;
}
memset(pre,0,sizeof(pre));
pre[0]=1;
for (int i=1;i<=5000;i++)
pre[i]=(1LL*pre[i-1]*i)%modp;
int ans=1;
ans=(1LL*ans*solve(a,b))%modp;
ans=(1LL*ans*solve(b,c))%modp;
ans=(1LL*ans*solve(a,c))%modp;
printf("%d\n",ans);
return 0;
}
|
869
|
D
|
The Overdosing Ubiquity
|
The fundamental prerequisite for justice is not to be correct, but to be strong. That's why justice is always the victor.
The Cinderswarm Bee. Koyomi knows it.
The bees, according to their nature, live in a tree. To be more specific, a \underline{complete binary tree} with $n$ nodes numbered from $1$ to $n$. The node numbered $1$ is the root, and the parent of the $i$-th ($2 ≤ i ≤ n$) node is $\textstyle{\left|{\frac{1}{2}}\right|}$. Note that, however, all edges in the tree are undirected.
Koyomi adds $m$ extra undirected edges to the tree, creating more complication to trick the bees. And you're here to count the number of \underline{simple paths} in the resulting graph, modulo $10^{9} + 7$. A \underline{simple path} is an alternating sequence of adjacent nodes and undirected edges, which begins and ends with nodes and does not contain any node more than once. Do note that a single node is also considered a valid \underline{simple path} under this definition. Please refer to the examples and notes below for instances.
|
Iterate over all possible combination, order and direction of extra edges. There are no more than $O(m!2^{m})$ ways to go through these extra edges, each of which will bring us at most $O(n^{2})$ more simple paths. If we count all these simple paths using simple depth-first search, the time complexity will be $O(n^{2}m!2^{m})$, which is the same as the order of the answer. However, we can reduce the original graph to a pretty small one, for example, by keeping all the nodes on some cycle and compressing the others. Noticing that the longest simple path on a complete binary tree is just $O(\log n)$, the compressed graph will contain at most $O(m\log n)$ nodes. Running simple depth-first search on such a small graph will lead to an $O((m\log n)^{2}m!2^{m})$ solution, which fits in with the small constraint of $m$ and works really fast in practice.
|
[
"brute force",
"dfs and similar",
"graphs"
] | 2,800
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
const int MAXN=255;
const int Mod=1000000007;
inline void add_mod(int &x,int y)
{
x=(x+y<Mod ? x+y : x+y-Mod);
}
int u[MAXN],v[MAXN];
map<int,int> mp;
inline int get_id(int x)
{
if(!mp[x])mp[x]=(int)mp.size();
return mp[x];
}
vector<int> e[MAXN];
void add_edge(int u,int v)
{
e[u].push_back(v);
e[v].push_back(u);
}
inline int cal_size(int u,int n,int d)
{
int t=u,c=0,res;
while(t)c++,t>>=1;
res=(1<<(d-c+1))-1,t=c;
while(t<d)t++,u=u<<1|1;
return res-max(min(u-n,1<<(d-c)),0);
}
int num[MAXN];
void pre_dp(int u,int f)
{
for(auto &v:e[u])
{
if(v==f)continue;
num[u]-=num[v];
pre_dp(v,u);
}
}
int vis[MAXN];
void dfs(int u,int &tot)
{
add_mod(tot,num[u]);
vis[u]=1;
for(auto &v:e[u])
if(!vis[v])dfs(v,tot);
vis[u]=0;
}
int main()
{
int n,m,d=0;
scanf("%d%d",&n,&m);
while((1<<d)<=n)d++;
get_id(1);
for(int i=0;i<m;i++)
{
scanf("%d%d",&u[i],&v[i]);
int t=u[i];
while(t)get_id(t),t>>=1;
t=v[i];
while(t)get_id(t),t>>=1;
}
for(auto &t:mp)
{
int u=t.first,id=t.second;
if(u>1)add_edge(get_id(u),get_id(u>>1));
num[id]=cal_size(u,n,d);
}
pre_dp(1,0);
for(int i=0;i<m;i++)
add_edge(get_id(u[i]),get_id(v[i]));
int res=0;
for(int i=1;i<=(int)mp.size();i++)
{
int tot=0;
dfs(i,tot);
add_mod(res,1LL*tot*num[i]%Mod);
}
printf("%d\n",res);
return 0;
}
|
869
|
E
|
The Untended Antiquity
|
Adieu l'ami.
Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.
The space is represented by a rectangular grid of $n × m$ cells, arranged into $n$ rows and $m$ columns. The $c$-th cell in the $r$-th row is denoted by $(r, c)$.
Oshino places and removes barriers \textbf{around} rectangular areas of cells. Specifically, an action denoted by "$1 r_{1} c_{1} r_{2} c_{2}$" means Oshino's placing barriers around a rectangle with two corners being $(r_{1}, c_{1})$ and $(r_{2}, c_{2})$ and sides parallel to squares sides. Similarly, "$2 r_{1} c_{1} r_{2} c_{2}$" means Oshino's removing barriers around the rectangle. \textbf{Oshino ensures that no barriers staying on the ground share any common points, nor do they intersect with boundaries of the $n × m$ area.}
Sometimes Koyomi tries to walk from one cell to another carefully without striding over barriers, in order to avoid damaging various items on the ground. "$3 r_{1} c_{1} r_{2} c_{2}$" means that Koyomi tries to walk from $(r_{1}, c_{1})$ to $(r_{2}, c_{2})$ without crossing barriers.
And you're here to tell Koyomi the feasibility of each of his attempts.
|
The barriers share no common points. Therefore two cells are connected iff the set of barriers containing each of them are the same. The reason is that no barrier can divide a barrier of larger area into two separate regions that are not reachable from each other. The inner barrier can't be any larger in either side (otherwise there will be common points), and thus cannot divide the outer one. The inner barrier can't be any larger in either side (otherwise there will be common points), and thus cannot divide the outer one. First approach: 2D segment tree or quadtree. In a 2D segment tree or quadtree, each node $u$ represents a rectangular area. On each node we use an array list (std::vector) to keep track of all barriers fully containing $u$'s represented rectangle. Each newly-added barrier will cause $O(\log^{2}n)$ insertions and each removal will result in $O(\log^{2}n)$ deletions. For queries, iterate over the list in all involved nodes (there are $O(\log n)$ of them). It can be proved that a node of size $w \times h$ with a corner $(r, c)$ can be contained in most $min{r - 1, c - 1, n - (r + h), m - (c + w)}$ barriers. Hence it can be shown that in the worst cases, a single query involves at most ${\textstyle{\frac{1}{2}}}\cdot n\cdot(\log_{2}n-1)$ elements in all lists. The total space complexity is $O(n^{2}\cdot\log^{2}n)$, and time complexity is $O(q\cdot n\cdot\log n)$, both with a small constant multiplier (less than $1 / 4$ for space and much less than $1 / 2$ for time), efficient enough to pass all tests. Tester's implementation works in under 800 ms in worst cases, so we decided to let such solutions pass. Also, a little randomization in partitioning may help avoid constructed worst cases and further reduce maximum running time on tests. Second approach: Randomization. We need to quickly check whether two sets are identical. Assign a random hash value to each barrier and use their sum or xor sum as the hash of the set. In this way, the creation/deletion of a barrier is equivalent to adding/subtracting/xoring a value to all cells in a rectangular region, and a query is equivalent to finding the values of two cells. The cells are reachable from each other iff their values are the same. This can be done efficiently with a 2D segment tree or 2D Fenwick tree, in $O(q\cdot\log^{2}n)$ time. With randomized values being 64-bit unsigned integers, the probability of a collision is $2^{ - 64}$. The probability to give $10^{5}$ correct answers is $(1 - 2^{ - 64})^{100 000} \approx 1 - 2^{ - 47}$. And the probability to give correct answers on all tests is approximately $1 - 2^{ - 40}$. If you're still afraid of collisions, you can: either (1) use a pair of 64-bit integers as the hash value, or (2) use the problemsetter's birthday, $20001206$, as the seed (kidding, lol). We are aware that a few implementations with sub-optimal time complexities passed all the tests, though we spared no effort in the preparation process to come up with various cases. We really look forward to doing better to eliminate all such possibilities in the future. Cheers! Tommyr7: I do hope you all enjoyed yourselves during the contest. See you next time!
|
[
"data structures",
"hashing"
] | 2,400
|
#include <bits/stdc++.h>
#define Maxn 2507
using namespace std;
int n,m,q;
map<pair<pair<int,int>,pair<int,int> >,pair<unsigned long long,unsigned long long> > mp;
pair<unsigned long long,unsigned long long> s[Maxn][Maxn];
void add(int x,int y,pair<unsigned long long,unsigned long long> del)
{
for (int kx=x;kx<=2503;kx+=kx&(-kx))
for (int ky=y;ky<=2503;ky+=ky&(-ky))
{
s[kx][ky].first+=del.first;
s[kx][ky].second+=del.second;
}
}
pair<unsigned long long,unsigned long long> query(int x,int y)
{
pair<unsigned long long,unsigned long long> res=make_pair(0,0);
for (int kx=x;kx;kx-=kx&(-kx))
for (int ky=y;ky;ky-=ky&(-ky))
{
res.first+=s[kx][ky].first;
res.second+=s[kx][ky].second;
}
return res;
}
int main()
{
scanf("%d%d%d",&n,&m,&q);
memset(s,0,sizeof(s));
srand(20001206);
mp.clear();
for (int i=1;i<=q;i++)
{
int t,r1,c1,r2,c2;
scanf("%d%d%d%d%d",&t,&r1,&c1,&r2,&c2);
pair<unsigned long long,unsigned long long> del,udel;
if (t==1)
{
del.first=rand();
del.second=rand();
udel=make_pair(-del.first,-del.second);
mp[make_pair(make_pair(r1,c1),make_pair(r2,c2))]=del;
add(r1,c1,del);
add(r1,c2+1,udel);
add(r2+1,c1,udel);
add(r2+1,c2+1,del);
} else if (t==2)
{
del=mp[make_pair(make_pair(r1,c1),make_pair(r2,c2))];
mp[make_pair(make_pair(r1,c1),make_pair(r2,c2))]=make_pair(0,0);
udel=make_pair(-del.first,-del.second);
add(r1,c1,udel);
add(r1,c2+1,del);
add(r2+1,c1,del);
add(r2+1,c2+1,udel);
}
else
{
del=query(r1,c1);
udel=query(r2,c2);
if (del==udel) printf("Yes\n"); else printf("No\n");
}
}
return 0;
}
|
870
|
A
|
Search for Pretty Integers
|
You are given two lists of non-zero digits.
Let's call an integer pretty if its (base $10$) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
|
Note that the length of the answer does not exceed two because we can take one number from the first list and one number from the second lists and make up of them a pretty number. So we need to check two cases: 1) Iterate through the digits from the first list and check if digit belongs to the second list too. Make up the number of this digit. 2) Iterate through the numbers from the first list and from the second list. Make up the number of this two digits. There are two ways: digit from the first list, then from the second list and vice versa. Then you should choose the minimal number.
|
[
"brute force",
"implementation"
] | 900
|
n, m = [int(i) for i in input().split()]
a = set(int(i) for i in input().split())
b = set(int(i) for i in input().split())
if a & b:
print(min(a & b))
else:
x = min(a)
y = min(b)
print(min(x, y), max(x, y), sep='')
|
870
|
B
|
Maximum of Maximums of Minimums
|
You are given an array $a_{1}, a_{2}, ..., a_{n}$ consisting of $n$ integers, and an integer $k$. You have to split the array into exactly $k$ non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the $k$ obtained minimums. What is the maximum possible integer you can get?
Definitions of subsegment and array splitting are given in notes.
|
To solve the problem, we need to consider three cases: $k \ge 3:$ then let $pos_max$ be the position of the element with the maximum value, then it is always possible to divide the array into subsegments so that one subsegment contains only this number, so the answer to the problem is $a_{pos_max}$. $k = 2:$ then all possible partitions are some prefix of nonzero length and coresponding suffix of nonzero length. You can iterate through all positions of the prefix end, and calculate the answer for this fixed partition, that equals to maximum of minima on the prefix and on the suffix. Minimum value for all suffixes and prefixes can be counted in advance. The answer is the maximum of the answers for all possible partitions. *Also it can be proved that for $k = 2$ the answer is the maximum of the first and last element. $k = 1:$ then the only possible partition is one segment equal to the whole array. So the answer is the minimum value on the whole array.
|
[
"greedy"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)1e5;
int a[MAXN];
int n, k;
int suf_min[MAXN];
int main()
{
cin >> n >> k;
for (int i = 0; i < n; ++i)
cin >> a[i];
if (k == 1)
{
int ans = a[0];
for (int i = 0; i < n; ++i)
ans = min(ans, a[i]);
cout << ans << endl;
}
else
if (k == 2)
{
suf_min[n - 1] = a[n - 1];
for (int i = n - 2; i >= 0; --i)
suf_min[i] = min(a[i], suf_min[i + 1]);
int pref_min = a[0];
int ans = max(pref_min, suf_min[1]);
for (int i = 1; i < n - 1; ++i)
{
pref_min = min(pref_min, a[i]);
ans = max(ans, max(suf_min[i + 1], pref_min));
}
cout << ans << endl;
}
else
{
int ans = a[0];
for (int i = 0; i < n; ++i)
ans = max(ans, a[i]);
cout << ans << endl;
}
return 0;
}
|
870
|
C
|
Maximum splitting
|
You are given several queries. In the $i$-th query you are given a single positive integer $n_{i}$. You are to represent $n_{i}$ as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than $1$ is composite, if it is not prime, i.e. if it has positive divisors not equal to $1$ and the integer itself.
|
Note that minimal composite number is equal to 4. So it is quite logical that there will be a lot of 4 in splitting of big numbers. Let's write for small numbers ($1 \le M \le n$) $dp_{n}$ - number of composite summands in splitting of $n$. If our query $n$ is small number let's print $dp_{n}$. Else let's find minimal number $k$ such that $n - 4 \cdot k$ is small number. Then print $k + dp_{n - 4 \cdot k}$. We can find $dp_{n}$ in $O(M^{2})$ or any other reasonable complexity. We even can find all $dp_{n}$ by hands if we set $M$ to $15$ or something like that (it will be proved later that $15$ is enough). So now we have right solution but it is not obvious why this solution works. Proof (not very beautiful but such thoughts can lead to correct solution): Let's find answer for all numbers from $1$ to $15$. Several observations: 1) Only 4, 6, 9 occurs in optimal splittings. 2) It is not beneficial to use 6 or 9 more than once because $6 + 6 = 4 + 4 + 4$, $9 + 9 = 6 + 6 + 6$. 3) 12, 13, 14, 15 have valid splittings. Let's prove that all numbers that are greater than 15 will have 4 in optimal splitting. Let's guess that it is incorrect. If minimal number in splitting is neither 4 nor 6 nor 9 than this number will have some non-trivial splitting by induction. If this number either 6 or 9 and we will decrease query by this number then we will sooner or later get some small number (which is less or equal than $15$). There is no splitting of small numbers or it contains 4 in splitting (and it contradicts with minimality of the first number) or it contains 6 and 9. So we have contradiction in all cases. We can subtract 4 from any big query and our solution is correct.
|
[
"dp",
"greedy",
"math",
"number theory"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 16;
signed main() {
ios_base::sync_with_stdio(false); cin.tie(0);
vector<int> ans(maxn, -1);
ans[0] = 0;
for (int i = 1; i < maxn; ++i) {
for (auto j: vector<int>{4, 6, 9}) {
if (i >= j && ans[i - j] != -1) {
ans[i] = max(ans[i], ans[i - j] + 1);
}
}
}
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
if (n < maxn) {
cout << ans[n] << '\n';
} else {
int t = (n - maxn) / 4 + 1;
cout << t + ans[n - 4 * t] << '\n';
}
}
}
|
870
|
D
|
Something with XOR Queries
|
This is an interactive problem.
Jury has hidden a permutation $p$ of integers from $0$ to $n - 1$. You know only the length $n$. Remind that in permutation all integers are distinct.
Let $b$ be the inverse permutation for $p$, i.e. $p_{bi} = i$ for all $i$. The only thing you can do is to ask xor of elements $p_{i}$ and $b_{j}$, printing two indices $i$ and $j$ (not necessarily distinct). As a result of the query with indices $i$ and $j$ you'll get the value $p_{i}\oplus b_{j}$, where $\mathbb{C}$ denotes the xor operation. You can find the description of xor operation in notes.
Note that some permutations can remain indistinguishable from the hidden one, even if you make all possible $n^{2}$ queries. You have to compute the number of permutations indistinguishable from the hidden one, and print one of such permutations, making no more than $2n$ queries.
The hidden permutation does not depend on your queries.
|
The statement: those and only those permutations whose answers to the queries $(0, i)$ and $(i, 0)$ for all $i$ coincide with the answers given to the program, are suitable for all possible queries. The proof: $p_{i}\oplus b_{j}=(p_{i}\oplus b_{0})\oplus(p_{0}\oplus b_{j})\oplus(p_{0}\oplus b_{0})$, which means that with the answers to the queries $(0, i)$ and $(i, 0)$ you can restore the answers to all other queries. If we fix the value $b_{0}$, then we can restore the whole permutation, since we know the answers to the queries $(i, 0)$, and $p_{i}=(p_{i}\oplus b_{0})\oplus b_{0}$. You can iterate through the value $b_{0}$, restore the whole permutation, and if there were no contradictions in it (that is, every number from $0$ to $n - 1$ occurs $1$ time) and for all $i$ values $p_{0}\oplus b_{i}$ and $p_{i}\oplus b_{0}$ coincide with the answers given to the program, then this permutation is indistinguishable from the hidden permutation. The answer is the number of such permutations, and one of such permutations.
|
[
"brute force",
"interactive",
"probabilities"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)5e3;
const int MAX_QUESTIONS_CNT = 2 * MAXN;
const int E_QUESTIONS_LIMIT_EXCEEDED = 1;
const int E_SMART_TEST_NOT_EQUAL_STUPID_TEST = 2;
const int E_WA = 3;
int n;
int P[MAXN], B[MAXN], ANSWERS_CNT;
int questions[MAXN][MAXN];
int questions_cnt;
int que(int x, int y)
{
if (questions[x][y] != -1)
return questions[x][y];
++questions_cnt;
if (questions_cnt > MAX_QUESTIONS_CNT)
exit(E_QUESTIONS_LIMIT_EXCEEDED);
cout << "? " << x << " " << y << "\n";
cout.flush();
int res;
cin >> res;
questions[x][y] = res;
return res;
}
int smart_test(vector <int>& p)
{
int n = p.size();
vector <int> b(n);
for (int i = 0; i < n; ++i)
b[p[i]] = i;
for (int i = 0; i < n; ++i)
if (que(0, i) != (p[0] ^ b[i]))
return 0;
for (int i = 0; i < n; ++i)
if (que(i, 0) != (p[i] ^ b[0]))
return 0;
return 1;
}
void answer(vector <int>& ans, int answers_cnt)
{
cout << "!\n";
cout << answers_cnt << "\n";
for (int i = 0; i < ans.size(); ++i)
cout << ans[i] << " ";
cout << "\n";
cout.flush();
}
void init()
{
memset(questions, -1, sizeof questions);
questions_cnt = 0;
cin >> n;
}
void solve()
{
int answers_cnt = 0;
init();
vector <int> ans;
vector <int> p(n), t(n);
for (int b0 = 0; b0 < n; ++b0)
{
int flag = 1;
for (int i = 0; i < n; ++i)
t[i] = 0;
for (int i = 0; i < n; ++i)
{
p[i] = que(i, 0) ^ b0;
if (p[i] > n || t[p[i]])
{
flag = 0;
break;
}
t[p[i]] = 1;
}
if (flag && smart_test(p))
{
++answers_cnt;
if (ans.size() == 0)
ans = p;
}
}
answer(ans, answers_cnt);
}
int main()
{
solve();
return 0;
}
|
870
|
E
|
Points, Lines and Ready-made Titles
|
You are given $n$ distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.
You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo $10^{9} + 7$.
|
Let's build graph on points. Add edge from point to left, right, top and bottom neighbours (if such neigbour exist). Note that we can solve problem independently for each connected component and then print product of answer for components. So we can consider only connected graphs without loss of generality. Let's define X as number of different x-coords, Y as number of different y-coords. What if graph contains some cycle? Let's consider this cycle without immediate vertices (vertices that lie on the same line with previous and next vertices of cycle). Draw a line from each such vertex to the next vertex of cycle (and from last to the first). We got all lines that are corresponding to x-coords and y-coords of vertices of cycle. Let's prove by induction that we can got all such lines from the whole graph Run depth-first search from vertices of cycle. Let we enter in some vertex that is not from cycle. It mush have at least one visited neighbour. By induction for graph consisting of visited vertices we can get all lines. So there is line from visited neighbour. Draw line in another direction and continue depth-first search. Sooner or later we will get all lines for the whole graph. Please note that intermediate vertices of cycle will be processed correctly too. If we can get all lines the we can get all subsets of lines. Answer for cyclic graph is $2^{X + Y}$. Now look at another case - acyclic graph or tree. We can prove that we can get any incomplete subset of lines. Let's fix subset and some line not from this subset. Just draw this line without restriction. By similar induction as in cyclic graph case we can prove that we can get all lines (but fixed line doesn't exist really). Now let's prove that it is impossible to take all lines. For graph consisting of only one vertex it is obvious. Else fix some leaf. We must draw a line which are not directed to any neigbour because it is the only way to draw this line. But now we have tree with less number of vertices. So our statement is correct by induction. Answer for tree is $2^{X + Y} - 1$. So the problem now is just about building graph on points and checking each component on having cycles.
|
[
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
struct point {
int x, y;
};
int binpow(int x, int p) {
if (p == 0) return 1;
if (p & 1) return binpow(x, p - 1) * x % mod;
return binpow(x * x % mod, p >> 1);
}
int n;
vector<point> pt;
vector< pair<int, int> > vertical[maxn];
vector< pair<int, int> > horizontal[maxn];
vector<int> graph[maxn];
char used[maxn];
set<int> different_x, different_y;
int component_size, sum_of_degree;
void dfs(int v) {
used[v] = true;
++component_size;
sum_of_degree += graph[v].size();
different_x.insert(pt[v].x);
different_y.insert(pt[v].y);
for (auto to: graph[v]) {
if (!used[to]) {
dfs(to);
}
}
}
signed main() {
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n;
pt.resize(n);
for (int i = 0; i < n; ++i) {
cin >> pt[i].x >> pt[i].y;
}
vector<int> x, y;
for (int i = 0; i < n; ++i) {
x.push_back(pt[i].x);
y.push_back(pt[i].y);
}
sort(x.begin(), x.end());
sort(y.begin(), y.end());
for (int i = 0; i < n; ++i) {
pt[i].x = lower_bound(x.begin(), x.end(), pt[i].x) - x.begin();
pt[i].y = lower_bound(y.begin(), y.end(), pt[i].y) - y.begin();
}
for (int i = 0; i < n; ++i) {
vertical[pt[i].x].emplace_back(pt[i].y, i);
horizontal[pt[i].y].emplace_back(pt[i].x, i);
}
for (int x = 0; x < n; ++x) {
sort(vertical[x].begin(), vertical[x].end());
for (int i = 1; i < vertical[x].size(); ++i) {
int a = vertical[x][i].second;
int b = vertical[x][i - 1].second;
graph[a].push_back(b);
graph[b].push_back(a);
}
}
for (int y = 0; y < n; ++y) {
sort(horizontal[y].begin(), horizontal[y].end());
for (int i = 1; i < horizontal[y].size(); ++i) {
int a = horizontal[y][i].second;
int b = horizontal[y][i - 1].second;
graph[a].push_back(b);
graph[b].push_back(a);
}
}
int ans = 1;
for (int i = 0; i < n; ++i) {
if (!used[i]) {
dfs(i);
int k = binpow(2, different_x.size() + different_y.size());
if (sum_of_degree / 2 == component_size - 1) --k;
ans = ans * k % mod;
different_x.clear();
different_y.clear();
sum_of_degree = 0;
component_size = 0;
}
}
cout << ans << '\n';
}
|
870
|
F
|
Paths
|
You are given a positive integer $n$. Let's build a graph on vertices $1, 2, ..., n$ in such a way that there is an edge between vertices $u$ and $v$ if and only if $\operatorname*{gcd}(u,v)\neq1$. Let $d(u, v)$ be the shortest distance between $u$ and $v$, or $0$ if there is no path between them. Compute the sum of values $d(u, v)$ over all $1 ≤ u < v ≤ n$.
The $gcd$ (greatest common divisor) of two positive integers is the maximum positive integer that divides both of the integers.
|
Integer $1 \le x \le n$ is bad is $x = 1$ or $x$ is prime and $x > n / 2$. Otherwise integer is good. $prime_{x}$ for $1 < x \le n$ is minimal prime divisor of $x$. Path between two vertices doesn't exist if at least one of them is bad. Distance equals to zero if this two vertices are the same. Distance equals to one if their numbers have common divisor. Distance between vertices $u$ and $v$ equals to two if $prime_{u} \cdot prime_{v} \le n$. Otherwise distance is three because path $u\rightarrow2\cdot p r i m e_{u}\rightarrow2\cdot p r i m e_{v}\rightarrow v$ always exists. It is easy to find number of pairs of vertices between which there is no path. Number of pairs with distance 1 equals to sum over all good $x$ of expressions $x - 1 - \phi (x)$. Number of pairs with distance 3 can be found if we subtract number of pairs without path and number of pairs with distances 0 and 1 from number of all pairs. So it only remains to find number of pairs with distance 2. Let's divide such pairs on three types 1) Pairs of coprime composite numbers. 2) Good prime $p$ and good number $x$ such as $prime_{p} \cdot prime_{x} \le n$ and $x$ is not divided by $p$. 3) Two different good prime numbers, product of which is less or equal than $n$. Number of pairs with distance 2 equals to number of pairs of the first and the second types minus number of pairs of the third type. Number of pairs of the first type equals to sum over all composite $1 \le x \le n$ of expressions $ \phi (x) - ((number of noncomposite numbers which are less than x) - number of unique prime divisors of x)$. For the second type we should sum up over all prime $p$ number of good numbers $x$ such that $prime_{p} \cdot prime_{x} \le n$ and subtract number of such numbers divided by $p$. The first we can calculate with some additional precalculations, for the second we can just check all numbers divided by $p$. Number of the pairs of the third type can be found trivially.
|
[
"data structures",
"number theory"
] | 2,700
|
#include <iostream>
using namespace std;
using ll = long long;
const int maxn = 1e7 + 5;
int n;
int prime[maxn];
char bad[maxn];
int phi[maxn];
int number_of_prime_divisors[maxn];
int pref_smallest_prime[maxn];
int number_of_bad = 0;
void calc_arrays() {
for (int i = 1; i <= n; ++i) {
phi[i] = i;
}
for (int i = 2; i <= n; ++i) {
if (prime[i]) continue;
for (int j = i; j <= n; j += i) {
if (!prime[j]) prime[j] = i;
phi[j] /= i;
phi[j] *= i - 1;
}
}
for (int i = 1; i <= n; ++i) {
if (i == 1 || prime[i] == i && i * 2 > n) {
bad[i] = true;
++number_of_bad;
}
}
for (int i = 2; i <= n; ++i) {
if (prime[i] == i) {
number_of_prime_divisors[i] = 1;
} else if (prime[i / prime[i]] == prime[i]) {
number_of_prime_divisors[i] = number_of_prime_divisors[i / prime[i]];
} else {
number_of_prime_divisors[i] = number_of_prime_divisors[i / prime[i]] + 1;
}
}
}
ll get_dist_one() {
ll ans = 0;
for (int i = 2; i <= n; ++i) {
if (!bad[i]) {
ans += i - 1 - phi[i];
}
}
return ans;
}
ll get_dist_two() {
ll ans = 0;
int pref_noncomposite = 1;
for (int i = 2; i <= n; ++i) {
if (prime[i] != i) {
ans += phi[i];
ans -= pref_noncomposite;
ans += number_of_prime_divisors[i];
} else {
++pref_noncomposite;
}
}
for (int i = 1; i <= n; ++i) {
if (!bad[i]) {
++pref_smallest_prime[prime[i]];
}
}
for (int i = 1; i <= n; ++i) {
pref_smallest_prime[i] += pref_smallest_prime[i - 1];
}
for (int i = 2; i <= n; ++i) {
if (prime[i] != i || bad[i]) continue;
ans += pref_smallest_prime[n / i];
for (int j = i; j <= n; j += i) {
if (prime[j] <= n / i) {
--ans;
}
}
}
for (int i = 2; i <= n; ++i) {
int a = prime[i];
int b = i / a;
if (b != 1 && prime[b] == b && a != b) {
--ans;
}
}
return ans;
}
ll solve(int _n) {
n = _n;
calc_arrays();
ll cnt_one = get_dist_one();
ll cnt_two = get_dist_two();
ll cnt_three = (ll) (n - number_of_bad) * (n - number_of_bad - 1) / 2 - cnt_one - cnt_two;
return cnt_one * 1 + cnt_two * 2 + cnt_three * 3;
}
int main() {
int n;
cin >> n;
cout << solve(n) << endl;
}
|
871
|
E
|
Restore the Tree
|
Petya had a tree consisting of $n$ vertices numbered with integers from $1$ to $n$. Accidentally he lost his tree.
Petya remembers information about $k$ vertices: distances from each of them to each of the $n$ tree vertices.
Your task is to restore any tree that satisfies the information that Petya remembers or report that such tree doesn't exist.
|
In the beginning, it should be noted that it is possible to find out numbers of vertices from which distances are given, the number of the $i$th specified vertex is $id_{i}$, such that $d_{i, idi} = 0$. If there is no such a vertex, or more than one, then there is no answer. Fix the $root$ equal to some vertex from which distances are given in the input data. Assume $root = id_{1}$. For any vertex $id_{i}$, we can find vertices lying in the path from $root$ to this vertex, since for such and only for such vertices $d_{1, v} + d_{i, v} = d_{1, idi}$. And accordingly, the vertex $v$ suitable for this condition will be at a distance $d_{1, v}$ from $root$. So, we have learned to build a part of a tree that consists of vertices that lie on the path from $root$ to some vertex $id_{i}$. If we couldn't build the path in such a way, then there is no answer. Time complexity of this phase is $O(nk)$. Now consider the remaining vertices, in order of increasing depth (distance to the root). Let's consider a fixed vertex $v$, look at the path from it to $root$, this path can be divided into $2$ parts - $(root, u), (u, v)$ where $u$ is the vertex from the already constructed tree, let's find the deepest of such $u$, this can be done with $O(k)$ operations by using the fact that $u$ is the deepest vertex among all $lca(v, id_{i})$, which equals the vertex on the path from $root$ to $id_{i}$ at a depth of $d_{1, idi} + d_{1, v} - d_{i, v}$. Then the ancestor $v$ is the vertex that was added in the same way to the subtree $u$ but with a depth of $1$ less, or the vertex $u$ (if the depth $u$ is $1$ less than the depth of the vertex $v$). If no such vertices have been added yet, then there is no answer, since we considered the vertices in order of increasing depth. Time complexity of adding each vertex is $O(k)$. The resulting tree is also the desired tree. Time complexity of the whole algorithm is $O(nk)$.
|
[
"graphs",
"greedy",
"trees"
] | 2,900
|
#include <bits/stdc++.h>
using namespace std;
void impossible() {
puts("-1");
exit(0);
}
int main() {
int n, k;
assert(scanf("%d %d", &n, &k) == 2);
assert(k > 0);
vector <int> dist[k];
vector <int> idx(n, 0);
for (int i = 0; i < k; ++i) {
dist[i] = vector <int> (n, 0);
for (int j = 0; j < n; ++j)
assert(scanf("%d", &dist[i][j]) == 1);
idx[i] = -1;
for (int j = 0; j < n; ++j) {
if (dist[i][j] == 0) {
if (idx[i] != -1)
impossible();
else
idx[i] = j;
}
}
if (idx[i] == -1)
impossible();
for (int j = 0; j < i; ++j)
if (idx[i] == idx[j])
impossible();
}
vector <int> p(n, -1);
vector <int> h = dist[0];
int root = idx[0];
vector <int> ps[k];
for (int i = 0; i < k; ++i)
ps[i] = vector <int> ();
for (int t = 1; t < k; ++t) {
int v = idx[t];
vector <int> &d = dist[t];
vector <int> pars(n, -1);
for (int u = 0; u < n; ++u) {
if (h[u] + d[u] == h[v]) {
if (pars[h[u]] != -1)
impossible();
pars[h[u]] = u;
}
}
for (int i = 0; i < n; ++i) {
if (pars[i] == -1 && i <= h[v])
impossible();
if (pars[i] != -1 && i > h[v])
impossible();
}
for (int i = 0; i < h[v]; ++i) {
int pu = pars[i];
int u = pars[i + 1];
if (p[u] != -1 && p[u] != pu)
impossible();
p[u] = pu;
}
ps[t] = pars;
}
if (p[root] != -1)
impossible();
vector <int> subs[n];
for (int i = 0; i < n; ++i)
subs[i] = vector <int> ();
vector <int> vh[n];
for (int i = 0; i < n; ++i)
vh[i] = vector <int> ();
for (int v = 0; v < n; ++v)
vh[h[v]].push_back(v);
for (int hh = 0; hh < n; ++hh) {
for (int v: vh[hh]) {
if (v == root || p[v] != -1)
continue;
int lp = root;
int lt = 0;
for (int t = 1; t < k; ++t) {
int u = idx[t];
vector <int> &d = dist[t];
vector <int> &pars = ps[t];
// h[v] + h[u] - 2 * h[l] == d[v]
// 2 * h[l] == h[v] + h[u] - d[v]
int hl2 = h[v] + h[u] - d[v];
if (hl2 % 2 != 0)
impossible();
int hl = hl2 / 2;
if (hl < 0 || hl > h[u] || hl > h[v])
impossible();
int l = pars[hl];
if (h[l] >= h[lp]) {
if (pars[h[lp]] != lp)
impossible();
lp = l;
lt = t;
} else {
if (ps[lt][h[l]] != l)
impossible();
}
}
subs[lp].push_back(v);
}
}
for (int i = 0; i < n; ++i) {
int prev = i;
int nxt = -1;
for (int v: subs[i]) {
assert(prev != -1);
if (h[v] == h[prev] + 1) {
p[v] = prev;
nxt = v;
} else {
prev = nxt;
if (prev != -1 && h[v] == h[prev] + 1) {
p[v] = prev;
nxt = v;
} else
impossible();
}
}
}
for (int i = 0; i < n; ++i) {
if (i == root)
assert(p[i] == -1);
else {
printf("%d %d\n", i + 1, p[i] + 1);
}
}
return 0;
}
|
873
|
A
|
Chores
|
Luba has to do $n$ chores today. $i$-th chore takes $a_{i}$ units of time to complete. It is guaranteed that for every $i\in[2...n]$ the condition $a_{i} ≥ a_{i - 1}$ is met, so the sequence is sorted.
Also Luba can work really hard on some chores. She can choose not more than $k$ any chores and do each of them in $x$ units of time instead of $a_{i}$ ($x<\operatorname*{min}_{i=1}a_{i}$).
Luba is very responsible, so she has to do all $n$ chores, and now she wants to know the minimum time she needs to do everything. Luba cannot do two chores simultaneously.
|
Since $x<\operatorname*{min}_{i=1}a_{i}$, it is better to do exactly $k$ chores in time $x$. And since we need to minimize total time we need to spend, it's better to speed up the "longest" chores. So the answer is $k\cdot x+\sum_{i=1}^{n-k}a_{i}$.
|
[
"implementation"
] | 800
| null |
873
|
B
|
Balanced Substring
|
You are given a string $s$ consisting only of characters 0 and 1. A substring $[l, r]$ of $s$ is a string $s_{l}s_{l + 1}s_{l + 2}... s_{r}$, and its length equals to $r - l + 1$. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length of the longest balanced substring of $s$.
|
Let $cnt_{0}(i)$ be the number of zeroes and $cnt_{1}(i)$ - the number of ones on prefix of length $i$; also let $balance(i) = cnt_{0}(i) - cnt_{1}(i)$ ($i \ge 0$). The interesting property of $balance$ is that the substring $[x, y]$ is balanced iff $balance(y) = balance(x - 1)$. That leads to a solution: for each value of $balance$ maintain the minimum $i$ where this $balance$ is obtained (let it be called $minIndex$), and for each index $i$ in the string update answer with $i - minIndex(balance(i))$.
|
[
"dp",
"implementation"
] | 1,500
| null |
873
|
C
|
Strange Game On Matrix
|
Ivan is playing a strange game.
He has a matrix $a$ with $n$ rows and $m$ columns. Each element of the matrix is equal to either $0$ or $1$. Rows and columns are $1$-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:
- Initially Ivan's score is $0$;
- In each column, Ivan will find the topmost $1$ (that is, if the current column is $j$, then he will find minimum $i$ such that $a_{i, j} = 1$). If there are no $1$'s in the column, this column is skipped;
- Ivan will look at the next $min(k, n - i + 1)$ elements in this column (starting from the element he found) and count the number of $1$'s among these elements. This number will be added to his score.
Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.
|
Let's notice that this task can be solved independently for each column, total result will be the sum of results for columns. The ones you should remove will always be the top ones in column. It makes no profit to erase some one while there are still ones on top of it, score won't become higher. Go from the top of the column to the bottom and recalculate the score after removing every one. Take the first position of the maximal score and update global answer with it. Overall complexity: $O(n^{3})$. $O(n^{2})$ can be achieved with partial sums.
|
[
"greedy",
"two pointers"
] | 1,600
| null |
873
|
D
|
Merge Sort
|
Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array $a$ with indices from $[l, r)$ can be implemented as follows:
- If the segment $[l, r)$ is already sorted in non-descending order (that is, for any $i$ such that $l ≤ i < r - 1$ $a[i] ≤ a[i + 1]$), then end the function call;
- Let $m i d=\lfloor{\frac{l+r}{2}}\rfloor$;
- Call $mergesort(a, l, mid)$;
- Call $mergesort(a, mid, r)$;
- Merge segments $[l, mid)$ and $[mid, r)$, making the segment $[l, r)$ sorted in non-descending order. The merge algorithm doesn't call any other functions.
The array in this problem is $0$-indexed, so to sort the whole array, you need to call $mergesort(a, 0, n)$.
The number of calls of function $mergesort$ is very important, so Ivan has decided to calculate it while sorting the array. For example, if $a = {1, 2, 3, 4}$, then there will be $1$ call of $mergesort$ — $mergesort(0, 4)$, which will check that the array is sorted and then end. If $a = {2, 1, 3}$, then the number of calls is $3$: first of all, you call $mergesort(0, 3)$, which then sets $mid = 1$ and calls $mergesort(0, 1)$ and $mergesort(1, 3)$, which do not perform any recursive calls because segments $(0, 1)$ and $(1, 3)$ are sorted.
Ivan has implemented the program that counts the number of $mergesort$ calls, but now he needs to test it. To do this, he needs to find an array $a$ such that $a$ is a permutation of size $n$ (that is, the number of elements in $a$ is $n$, and every integer number from $[1, n]$ can be found in this array), and the number of $mergesort$ calls when sorting the array is exactly $k$.
Help Ivan to find an array he wants!
|
First of all, if $k$ is even, then there is no solution, since the number of calls is always odd (one call in the beginning, and each call makes either $0$ or $2$ recursive calls). Then, if $k$ is odd, let's try to start with a sorted permutation and try to "unsort" it. Let's make a function $unsort(l, r)$ that will do it. When we "unsort" a segment, we can either keep it sorted (if we already made enough calls), or make it non-sorted and then call $unsort(l, mid)$ and $unsort(mid, r)$, if we need more calls. When we make a segment non-sorted, it's better to keep its both halves sorted; an easy way to handle this is to swap two middle element. It's easy to see that the number of $unsort$ calls is equal to the number of $mergesort$ calls to sort the resulting permutation, so we can use this approach to try getting exactly $k$ calls.
|
[
"constructive algorithms",
"divide and conquer"
] | 1,800
| null |
873
|
E
|
Awards For Contestants
|
Alexey recently held a programming contest for students from Berland. $n$ students participated in a contest, $i$-th of them solved $a_{i}$ problems. Now he wants to award some contestants. Alexey can award the students with diplomas of three different degrees. Each student either will receive one diploma of some degree, or won't receive any diplomas at all. Let $cnt_{x}$ be the number of students that are awarded with diplomas of degree $x$ ($1 ≤ x ≤ 3$). The following conditions must hold:
- For each $x$ ($1 ≤ x ≤ 3$) $cnt_{x} > 0$;
- For any two degrees $x$ and $y$ $cnt_{x} ≤ 2·cnt_{y}$.
Of course, there are a lot of ways to distribute the diplomas. Let $b_{i}$ be the degree of diploma $i$-th student will receive (or $ - 1$ if $i$-th student won't receive any diplomas). Also for any $x$ such that $1 ≤ x ≤ 3$ let $c_{x}$ be the maximum number of problems solved by a student that receives a diploma of degree $x$, and $d_{x}$ be the minimum number of problems solved by a student that receives a diploma of degree $x$. Alexey wants to distribute the diplomas in such a way that:
- If student $i$ solved more problems than student $j$, then he has to be awarded not worse than student $j$ (it's impossible that student $j$ receives a diploma and $i$ doesn't receive any, and also it's impossible that both of them receive a diploma, but $b_{j} < b_{i}$);
- $d_{1} - c_{2}$ is maximum possible;
- Among all ways that maximize the previous expression, $d_{2} - c_{3}$ is maximum possible;
- Among all ways that correspond to the two previous conditions, $d_{3} - c_{ - 1}$ is maximum possible, where $c_{ - 1}$ is the maximum number of problems solved by a student that doesn't receive any diploma (or $0$ if each student is awarded with some diploma).
Help Alexey to find a way to award the contestants!
|
Let's consider naive solution: make three loops to fix amounts of people to get dimplomas of each degree, take the best. Obviously, sorting the scores will regroup optimal blocks for each degree in such a way that they come in segments of initial array. We tried to make these solutions fail but underestimated the abilities of contestants to optimize this kind of stuff and couple of such made it to the end of contest. :( To be honest, we just need to get rid of the last loop. Let $b_{i}$ be the difference between $a_{i}$ and $a_{i + 1}$ ($a$ is sorted, $b_{n - 1} = a_{n - 1}$). Then let $i_{2}$ be the position of the last diploma of second degree and $cnt_{1}$, $cnt_{2}$ be the amounts of diplomas of the first ans the second degrees. Thus the best position to put the separator between the third degree and no diploma is the postion with the maximum number in array $b$ over segment $[i_{2}+m a x(1,[\frac{m a x(c n t_{1},c n t_{2})}{2}]),i_{2}+m i n(n-i_{2},2\cdot m i n(c n t_{1},c n t_{2}))]$. This are the borders of possible amount of the dimplomas of the third degree. Maximum over segment can be implemented with segment tree, sparse table or even naive square matrix with $O(n^{2})$ precalc time and $O(n^{2})$ memory. Overall complexity: $O(n^{2})$/$O(n^{2}\log{n})$.
|
[
"brute force",
"data structures",
"dp"
] | 2,300
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.