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
⌀ |
|---|---|---|---|---|---|---|---|
1054
|
G
|
New Road Network
|
The king of some country $N$ decided to completely rebuild the road network. There are $n$ people living in the country, they are enumerated from $1$ to $n$. It is possible to construct a road between the house of any citizen $a$ to the house of any other citizen $b$. There should not be more than one road between any pair of citizens. The road network must be connected, i.e. it should be possible to reach every citizen starting from anyone using roads. To save funds, it was decided to build exactly $n-1$ road, so the road network should be a tree.
However, it is not that easy as it sounds, that's why the king addressed you for help. There are $m$ secret communities in the country, each of them unites a non-empty subset of citizens. The king does not want to conflict with any of the communities, so he wants to build the network such that the houses of members of each society form a connected subtree in network. A set of vertices forms a connected subtree if and only if the graph remains connected when we delete all the other vertices and all edges but ones that connect the vertices from the set.
Help the king to determine if it is possible to build the desired road network, and if it is, build it.
|
Let us denote for Ai the set of sets (or secret comunities, as in our problem), which contains i-th vertex. Note that if some set Ai contains an element that does not belong to any other set Aj, it can be thrown out and it will not affect to the answer. Let's make this. Let the tree exist. Then it has a leaf (let this vertex i). Let the only edge from i be to vertex j. Any element Ai is contained in \ge 2-x sets and in the tree all sets (which secret comunities) form connected subtrees. This implies that Ai \subset Aj. So, if in A1, \dots ,An there are no two sets such that one subset of the other, then the tree does not exist. Otherwise, let us find any pair Ai \subset Aj. We prove that there exists a tree in which i is a leaf that has an edge to j. It is possible to change the edges of any tree-solution that i becomes a leaf that has an edge to j, but the tree will still be a solution (it is the exercise for the reader). Let's find a good pair (i,j), remove i and continue the process. At the same time, at each step, it is necessary to remove the elements contained in \le 1 sets. If we implement such an algorithm in this form it will work for O(n3 \cdot m/64) time, which is too big. To improve the algorithm's complexity, for each set Ai, we store a set of indices j, such that Ai \subset Aj. Then at each step, you can quickly find the needed pair (i,j). At the same time, removing i, you can quickly update this structure. In this problem, there is a simpler solution, but it is more difficult to prove it. Let's build a weighted undirected graph on n vertices with weight wij=|Ai \cap Aj|. Let's construct the maximum spanning tree in this graph. It is can be proved that either it is the answer, or there is no solution. This can be understood from the proof of the previous solution, which essentially simulates the search for such a spanning tree. Time complexity: O(n2 \cdot m/64).
|
[
"constructive algorithms",
"greedy",
"math"
] | 3,300
|
#include <iostream>
#include <tuple>
#include <sstream>
#include <vector>
#include <cmath>
#include <ctime>
#include <bitset>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<pii> vpi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
typedef pair<i64, i64> pi64;
typedef double ld;
template<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }
template<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }
const int maxn = 2011, maxm = 2011;
typedef bitset<maxm> bs;
bs b[maxn];
char buf[maxm];
int dist[maxn][maxn];
pii me[maxn];
int used[maxn];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
int T;
scanf("%d", &T);
while (T--) {
int n, m;
scanf("%d%d", &n, &m);
forn(i, n) forn(j, maxm) b[i][j] = 0;
vi cnt(m);
forn(i, m) {
scanf("%s", buf);
forn(j, n) if (buf[j] == '1') b[j].set(i), ++cnt[i];
}
forn(i, n) forn(j, n) {
dist[i][j] = (b[i] & b[j]).count();
}
forn(i, n) me[i] = {-1e9, -1}, used[i] = 0;
int Z = 0;
vector<pii> e;
forn(i, n) {
int v = -1;
forn(j, n) {
if (used[j]) continue;
if (v == -1 || me[j] > me[v]) v = j;
}
used[v] = 1;
if (me[v].se != -1) e.pb({v, me[v].se});
forn(j, n) uax(me[j], mp(dist[v][j], v));
}
bool ok = true;
forn(j, m) {
int z = 0;
for (auto w: e) if (b[w.fi][j] && b[w.se][j]) ++z;
ok &= z == cnt[j] - 1;
}
if (ok) {
cout << "YES\n";
for (auto w: e) cout << w.fi + 1 << ' ' << w.se + 1 << '\n';
} else cout << "NO\n";
}
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
|
1054
|
H
|
Epic Convolution
|
You are given two arrays $a_0, a_1, \ldots, a_{n - 1}$ and $b_0, b_1, \ldots, b_{m-1}$, and an integer $c$.
Compute the following sum:
$$\sum_{i=0}^{n-1} \sum_{j=0}^{m-1} a_i b_j c^{i^2\,j^3}$$
Since it's value can be really large, print it modulo $490019$.
|
The given modulo 490019 is a prime one. Note, that value of c(i2j3), according to the Fermat's theorem, depends only on the (i2j3)mod(490019-1). The main idea is that we want to end up with something like polynomial \sum ctxt, where t would be (i2j3)mod(490019-1) and ct is sum of corresponding aibj. If we have such a polynomial, we can easily compute the final answer. Now time to notice, that the given modulo was... a bit non standard. Notice, that phi=490019-1=490018=2 \cdot 491 \cdot 499. As chinese remainder theorem suggests, xmodphi is equivalent to (xmod2,xmod491,xmod499) (for all x) And instead of multiplying resiudes modulo phi we can multiply (and computing squares and cubes) the elements of this tuple pairwise. Let's ignore the first component for a while (suppose xmod2=0). Since the numbers 491 and 499 are prime, they have a primitive roots. Let's compute discrete logarithms of the residues of i2's and j3's modulo 491 and 499. (There is some trouble if the residue is zero, but let's skip for now). And now we left only with multiplication. But since we have taken log's multiplication becomes summation. So we can apply a polynomial multiplication to solve the problem. Basically, we have two polynomials of form \sum i,jci,jxiyj (from array a and array b), where i is logarithm of residue modulo 491 and j is logarithm of residue modulo 499. We can multiply these polynomials with fft! A 2d polynomial is matrix of it's coefficients. A 2d fft is matrix of it's values in (win,wjm). One can prove, that to have 2d fft we can just apply fft on all lines and then on all columns (or vice versa). The rest is as usual, multiply fft's values pointwise, then inverse fft and examine the result as we stated in the begining of editorial. We need to deal with cases when residue is equal to zero modulo 2, 491 or 499. Since the timelimit was really generous we can deal with latter two just by handling all pairs (i,j) where either i is zero modulo 491 or 499 or j is zero modulo 491 or 499 in a naive way. This is roughly nm/sqrt(mod) pairs which takes roughly a second with the given constraints. Residues modulo 2 must be handled specifically (because there are too much pairs), but it is easy since there are only two of them. Basically the end residue is 1 only if original residues are 1 as well.
|
[
"chinese remainder theorem",
"fft",
"math",
"number theory"
] | 3,500
|
// 2018, Sayutin Dmitry.
#include <bits/stdc++.h>
using std::cin;
using std::cout;
using std::cerr;
using std::vector;
using std::map;
using std::array;
using std::set;
using std::string;
using std::pair;
using std::make_pair;
using std::tuple;
using std::make_tuple;
using std::get;
using std::min;
using std::abs;
using std::max;
using std::unique;
using std::sort;
using std::generate;
using std::reverse;
using std::min_element;
using std::max_element;
#ifdef LOCAL
#define LASSERT(X) assert(X)
#else
#define LASSERT(X) {}
#endif
template <typename T>
T input() {
T res;
cin >> res;
LASSERT(cin);
return res;
}
template <typename IT>
void input_seq(IT b, IT e) {
std::generate(b, e, input<typename std::remove_reference<decltype(*b)>::type>);
}
#define SZ(vec) int((vec).size())
#define ALL(data) data.begin(),data.end()
#define RALL(data) data.rbegin(),data.rend()
#define TYPEMAX(type) std::numeric_limits<type>::max()
#define TYPEMIN(type) std::numeric_limits<type>::min()
#define pb push_back
#define eb emplace_back
const int mod = 490019;
const int phi = mod - 1; // = 2 * 491 * 499
int add(int a, int b) {
return (a + b >= mod ? a + b - mod : a + b);
}
int sub(int a, int b) {
return (a >= b ? a - b : mod + a - b);
}
int mult(int a, int b) {
return (int64_t(a) * b) % mod;
}
int fastpow(int a, int n, int md, int r = 1) {
while (n) {
if (n % 2)
r = (int64_t(r) * a) % md;
a = (int64_t(a) * a) % md;
n /= 2;
}
return r;
}
const int LOG_N = 10;
const int FFT_N = (1 << LOG_N);
struct complex {
complex(): x(0), y(0) {}
complex(double x, double y = 0): x(x), y(y) {}
complex operator+(complex other) {return complex(x + other.x, y + other.y);}
complex operator+=(complex other) {x += other.x; y += other.y; return *this;}
complex operator-(complex other) {return complex(x - other.x, y - other.y);}
complex operator*(complex other) {return complex(x * other.x - y * other.y, x * other.y + y * other.x);}
complex operator/=(int val) {x /= val; y /= val; return *this;}
inline double real() {return x;}
inline double imag() {return y;}
double x;
double y;
};
complex w[FFT_N];
int rev[FFT_N];
#if 1
void precalc() {
// /2 [0;1) -> [1;1]
// /4 [0;2) -> [2;3]
// /8 [0;4) -> [4;7]
// ..
// /FFT_N [0;FFT_N / 2) -> [FFT_N / 2; FFT_N - 1]
double pi = acos(-1);
for (int i = 0; i != FFT_N / 2; ++i)
w[FFT_N / 2 + i] = complex(cos(2.0 * pi * double(i) / FFT_N), sin(2.0 * pi * double(i) / FFT_N));
for (int n = FFT_N / 2; n >= 2; n /= 2)
for (int i = 0; i != n / 2; ++i)
w[n / 2 + i] = w[n + 2 * i];
rev[0] = 0;
int last = 0;
for (int i = 1; i != FFT_N; ++i) {
if (i == (2 << last))
++last;
rev[i] = rev[i ^ (1 << last)] | (1 << (LOG_N - 1 - last));
}
}
void fft(complex* a) {
for (int i = 0; i < FFT_N; ++i)
if (i < rev[i])
std::swap(a[i], a[rev[i]]);
for (int n = 1; n < FFT_N; n = n << 1)
for (int start = 0; start < FFT_N; start += (n << 1))
for (int off = 0; off < n; ++off) {
complex x = a[start + off];
complex y = a[start + off + n] * w[n + off];
a[start + off] = x + y;
a[start + off + n] = x - y;
}
}
#else
void precalc() {
double pi = acos(-1);
for (int i = 0; i != FFT_N; ++i)
w[i] = complex(cos(2.0 * pi * double(i) / FFT_N), sin(2.0 * pi * double(i) / FFT_N));
rev[0] = 0;
int last = 0;
for (int i = 1; i != FFT_N; ++i) {
if (i == (2 << last))
++last;
rev[i] = rev[i ^ (1 << last)] | (1 << (LOG_N - 1 - last));
}
}
void fft(complex* a) {
for (int i = 0; i < FFT_N; ++i)
if (i < rev[i])
std::swap(a[i], a[rev[i]]);
for (int lvl = 0; lvl < LOG_N; ++lvl)
for (int start = 0; start < FFT_N; start += (2 << lvl))
for (int off = 0; off < (1 << lvl); ++off) {
complex x = a[start + off];
complex y = a[start + off + (1 << lvl)] * w[off << (LOG_N - 1 - lvl)];
a[start + off + (0 << lvl)] = x + y;
a[start + off + (1 << lvl)] = x - y;
}
}
#endif
void inv_fft(complex* a) {
fft(a);
std::reverse(a + 1, a + FFT_N);
for (int i = 0; i != FFT_N; ++i)
a[i] /= FFT_N;
}
int inverse(int a, int md) {
return fastpow(a % md, md - 2, md);
}
// [0; phi) -> [0; 2) x [0; 491) x [0; 499)
tuple<int, int, int> chinese_it(int num) {
return make_tuple(num % 2, num % 491, num % 499);
}
void chinese_it(int num, int& a, int& b, int& c) {
a = num % 2;
b = num % 491;
c = num % 499;
}
// [0; 2) x [0; 491) x [0; 499) -> [0; phi)
int un_chinese_it(int a, int b, int c) {
static int X = (int64_t(491 * 499) * inverse(491 * 499, 2)) % phi;
static int Y = (int64_t(2 * 499) * inverse(2 * 499, 491)) % phi;
static int Z = (int64_t(2 * 491) * inverse(2 * 491, 499)) % phi;
return (a * X + b * Y + c * Z) % phi;
}
int primitive491 = 7;
int primitive499 = 7;
int pr_pows491[491];
int pr_pows499[499];
int log491[491];
int log499[499];
#ifndef LOCAL
#define STAMP(msg) {fprintf(stderr, "%0.2lf: %s\n", clock() / double(CLOCKS_PER_SEC), msg);}
#else
#define STAMP(msg)
#endif
int main() {
STAMP("start");
// code here
int n, m, c;
scanf("%d%d%d", &n, &m, &c);
vector<int> a(n);
vector<int> b(m);
for (int& elem: a)
scanf("%d", &elem);
for (int& elem: b)
scanf("%d", &elem);
vector<int> pows(phi);
pows[0] = 1;
for (int i = 1; i != phi; ++i)
pows[i] = mult(pows[i - 1], c);
// handle all "% 491 == 0" and "% 499 == 0"
vector<int> spec;
for (int i = 0; i < max(n, m); i += 491)
spec.push_back(i);
for (int i = 0; i < max(n, m); i += 499)
spec.push_back(i);
std::sort(ALL(spec));
spec.resize(std::unique(ALL(spec)) - spec.begin());
int res = 0;
STAMP("before");
fprintf(stderr, "spec: %d\n", SZ(spec));
for (int j = 0; j != m; ++j) {
int j3 = (j * int64_t(j) * j) % phi;
int64_t sum = 0;
for (int i: spec) {
if (i > n)
break;
int i2 = (i * int64_t(i)) % phi;
int k = a[i] * b[j];
sum += int64_t(k) * pows[(i2 * int64_t(j3)) % phi];
}
res = (res + sum) % mod;
}
STAMP("stage1 done");
for (int j: spec) {
int j3 = (j * int64_t(j) * j) % phi;
int64_t sum = 0;
for (int i = 0; i != n; ++i) {
int i2 = (i * int64_t(i)) % phi;
if (j > m)
break;
int k = (a[i] * b[j]);
sum += int64_t(k) * pows[(i2 * int64_t(j3)) % phi];
}
res = (res + sum) % mod;
}
STAMP("stage2 done");
for (int i: spec)
for (int j: spec) {
if (i > n or j > m)
break;
int k = (a[i] * b[j]);
int i2 = (i * int64_t(i)) % phi;
int j3 = (j * int64_t(j) * j) % phi;
res = (res - int64_t(k) * pows[(i2 * int64_t(j3)) % phi]) % mod;
if (res < 0)
res += mod;
}
STAMP("stage3 done");
pr_pows491[0] = 1;
for (int i = 1; i < 491; ++i)
pr_pows491[i] = (pr_pows491[i - 1] * primitive491) % 491;
for (int i = 0; i < 490; ++i)
log491[pr_pows491[i]] = i;
pr_pows499[0] = 1;
for (int i = 1; i < 499; ++i)
pr_pows499[i] = (pr_pows499[i - 1] * primitive499) % 499;
for (int i = 0; i < 498; ++i)
log499[pr_pows499[i]] = i;
STAMP("before ffts");
complex arr[2][1024][1024];
for (int i = 0; i != 2; ++i)
for (int j = 0; j != 1024; ++j)
for (int k = 0; k != 1024; ++k)
arr[i][j][k] = 0.0;
for (int i = 0; i != n; ++i) {
int x, y, z;
chinese_it(i, x, y, z);
if (y == 0 or z == 0)
continue;
y = (2 * log491[y]) % 490;
z = (2 * log499[z]) % 498;
arr[x][y][z] += complex(a[i], 0);
if (x == 1)
arr[0][y][z] += complex(a[i], 0);
}
for (int i = 0; i != m; ++i) {
int x, y, z;
chinese_it(i, x, y, z);
if (y == 0 or z == 0)
continue;
y = (3 * log491[y]) % 490;
z = (3 * log499[z]) % 498;
arr[x][y][z] += complex(0, b[i]);
if (x == 1)
arr[0][y][z] += complex(0, b[i]);
}
STAMP("prepare done");
precalc();
STAMP("precalc done");
for (int i = 0; i != 2; ++i) {
for (int j = 0; j != 1024; ++j)
fft(arr[i][j]);
complex tmp[1024];
for (int k = 0; k != 1024; ++k) {
for (int j = 0; j != 1024; ++j)
tmp[j] = arr[i][j][k];
fft(tmp);
for (int j = 0; j != 1024; ++j)
arr[i][j][k] = tmp[j];
}
}
STAMP("fft1");
for (int i = 0; i != 2; ++i)
for (int j = 0; j != 1024; ++j)
for (int k = 0; k != 1024; ++k)
arr[i][j][k] = arr[i][j][k] * arr[i][j][k];
STAMP("fft+fft");
for (int i = 0; i != 2; ++i) {
for (int j = 0; j != 1024; ++j)
inv_fft(arr[i][j]);
complex tmp[1024];
for (int k = 0; k != 1024; ++k) {
for (int j = 0; j != 1024; ++j)
tmp[j] = arr[i][j][k];
inv_fft(tmp);
for (int j = 0; j != 1024; ++j)
arr[i][j][k] = tmp[j];
}
}
STAMP("fft2");
// cout << "====\n";
for (int i = 0; i != 2; ++i)
for (int j = 0; j != 1024; ++j)
for (int k = 0; k != 1024; ++k) {
int64_t val = round(arr[i][j][k].imag() / 2.0);
if (i == 0)
val -= round(arr[1][j][k].imag() / 2.0);
val %= mod;
int ip = i;
int jp = pr_pows491[j % 490];
int kp = pr_pows499[k % 498];
res = (res + val * pows[un_chinese_it(ip, jp, kp)]) % mod;
}
STAMP("fi");
printf("%d\n", res);
return 0;
}
|
1055
|
A
|
Metro
|
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.
In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $n$ stations numbered from $1$ to $n$. Bob lives near the station with number $1$, while Alice lives near the station with number $s$. The metro line has two tracks. Trains on the first track go from the station $1$ to the station $n$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.
Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.
When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.
|
Either Bob may go directly to Alice's station, or if his train doesn't stop there, he will need to change trains as soon as possible to go in the opposite direction. It's not hard to prove that he may only need to change the trains once. If neither of the options are possible, then Bob can't come to Alice by train.
|
[
"graphs"
] | 900
| null |
1055
|
B
|
Alice and Hairdresser
|
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...
To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $l$ centimeters after haircut, where $l$ is her favorite number. Suppose, that the Alice's head is a straight line on which $n$ hairlines grow. Let's number them from $1$ to $n$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $l$, given that \textbf{all} hairlines on that segment had length \textbf{strictly greater} than $l$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.
Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types:
- $0$ — Alice asks how much time the haircut would take if she would go to the hairdresser now.
- $1$ $p$ $d$ — $p$-th hairline grows by $d$ centimeters.
Note, that in the request $0$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.
|
Let's consider number of current non-expandable segments that have all elements more than $l$. When an element (in this case a hairline) grows up, we can recalculate this number of segments looking at the neighbours.
|
[
"dsu",
"implementation"
] | 1,300
| null |
1055
|
C
|
Lucky Days
|
Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days $[l_a; r_a]$ are lucky, then there are some unlucky days: $[r_a + 1; l_a + t_a - 1]$, and then there are lucky days again: $[l_a + t_a; r_a + t_a]$ and so on. In other words, the day is lucky for Alice if it lies in the segment $[l_a + k t_a; r_a + k t_a]$ for some non-negative integer $k$.
The Bob's lucky day have similar structure, however the parameters of his sequence are different: $l_b$, $r_b$, $t_b$. So a day is a lucky for Bob if it lies in a segment $[l_b + k t_b; r_b + k t_b]$, for some non-negative integer $k$.
Alice and Bob want to participate in team competitions together and so they want to find out what is the largest possible number of consecutive days, which are lucky for both Alice and Bob.
|
All possible shifts of Alice's and Bobs' pattern periods are the multiples of $\mathrm{gcd}(t_a, t_b)$. You want to use such a shift that the start of their lucky days is as close as possible. Also if they can't coincide precisely, you need to try shifting in such way that Alice's lucky days start before Bob's, and the opposite.
|
[
"math",
"number theory"
] | 1,900
| null |
1055
|
D
|
Refactoring
|
Alice has written a program and now tries to improve its readability. One of the ways to improve readability is to give sensible names to the variables, so now Alice wants to rename some variables in her program. In her IDE there is a command called "massive refactoring", which can replace names of many variable in just one run. To use it, Alice needs to select two strings $s$ and $t$ and after that for each variable the following algorithm is performed: if the variable's name contains $s$ as a substring, then the first (and only first) occurrence of $s$ is replaced with $t$. If the name doesn't contain $s$, then this variable's name stays the same.
The list of variables is known and for each variable both the initial name and the name Alice wants this variable change to are known. Moreover, for each variable the lengths of the initial name and the target name are equal (otherwise the alignment of the code could become broken). You need to perform renaming of all variables in \textbf{exactly one} run of the massive refactoring command or determine that it is impossible.
|
Let's take all variable names that have changed. First observation is that if you trim coinciding prefixes and suffixes from the original variable names and the resulting name, you will find the part that needs to be changed. We will call it "the core" of the replacement. All those parts need to be exactly the same. However we don't want to create string $s$ that matches things that we don't want to get changed, so we will try to expand the pattern to the left and to the right as much as possible. Each time we will check if adjacent symbols coincide, and, if so, expand the pattern. In the end we will obtain longest possible $s$ and $t$ that may explain the differences. The final part is to check whether they actually work (this can be done with any kind of string search). Overall complexity is proportional to the size of the input.
|
[
"greedy",
"implementation",
"strings"
] | 2,400
| null |
1055
|
E
|
Segments on the Line
|
You are a given a list of integers $a_1, a_2, \ldots, a_n$ and $s$ of its segments $[l_j; r_j]$ (where $1 \le l_j \le r_j \le n$).
You need to select exactly $m$ segments in such a way that the $k$-th order statistic of the multiset of $a_i$, where $i$ is contained in at least one segment, is the smallest possible. If it's impossible to select a set of $m$ segments in such a way that the multiset contains at least $k$ elements, print -1.
The $k$-th order statistic of a multiset is the value of the $k$-th element after sorting the multiset in non-descending order.
|
Let's find the answer using binary search. Sort segments in the order of increasing right ends. Now we are solving the following problem: how many numbers $\le x$ we cover by $m$ segments. This may be solved with a DP along the scan line. We count how many numbers can we cover using at most $j$ of the first $i$ segments, making sure that we must always take the $i$-th segment. There are two options - either the new segment overlaps with the previous one, or not (we will ignore the case that two segments may be inside each other, because in the end it just means we can choose fewer than $m$ segments). In the case of overlap it's always optimal to choose the previous segment such that it spans as far as possible to the left (i.e. its left end is lowest). Which segment that would be for a given $i$ is easy to precompute. The case when the segments don't overlap can be implemented by a maintaining prefix maximum for all $j$. Overall complexity is $O(1500^2 \cdot \log 10^9)$.
|
[
"binary search",
"dp"
] | 2,500
| null |
1055
|
F
|
Tree and XOR
|
You are given a connected undirected graph without cycles (that is, a tree) of $n$ vertices, moreover, there is a non-negative integer written on every edge.
Consider all pairs of vertices $(v, u)$ (that is, there are exactly $n^2$ such pairs) and for each pair calculate the bitwise exclusive or (xor) of all integers on edges of the simple path between $v$ and $u$. If the path consists of one vertex only, then xor of all integers on edges of this path is equal to $0$.
Suppose we sorted the resulting $n^2$ values in non-decreasing order. You need to find the $k$-th of them.
The definition of xor is as follows.
Given two integers $x$ and $y$, consider their binary representations (possibly with leading zeros): $x_k \dots x_2 x_1 x_0$ and $y_k \dots y_2 y_1 y_0$ (where $k$ is any number so that all bits of $x$ and $y$ can be represented). Here, $x_i$ is the $i$-th bit of the number $x$ and $y_i$ is the $i$-th bit of the number $y$. Let $r = x \oplus y$ be the result of the xor operation of $x$ and $y$. Then $r$ is defined as $r_k \dots r_2 r_1 r_0$ where:
$$ r_i = \left\{ \begin{aligned} 1, ~ \text{if} ~ x_i \ne y_i \\ 0, ~ \text{if} ~ x_i = y_i \end{aligned} \right. $$
|
First observation is that we may first assign a number to each vertex that is equal to xor of all values on the path from this vertex to the root (the root itself will be assigned $0$). Then the value of any path will be equal to xor of the values written in its first and last vertices. Since the order of those values doesn't matter, let's build a binary trie of those numbers. In every node of the trie we will also store the number of values in its subtree. It's relatively easy to solve the reverse problem - to find number of paths having value not exceeding $v$. However the complexity of this is already $O(62 \cdot n)$, so adding binary search on top of it may not work. It's possible though to recover bits of the answer one by one by descending the trie level by level and maintaining the pairs of trie nodes that give us the correct higher bits of the answer (node may be in pair with itself). At each step let's find the number of paths, whose next bit equals to $0$. In order to do this, we will go over the list of pairs. In every pair there may be two ways of obtaining $0$ as the next bit of the result: the corresponding bits of the values in the trie can be both zeros or both ones. In both cases we may compute number of paths as a product of the number of values in the corresponding subtrees. Then we sum all those numbers up over all the pairs. If the sum is greater or equal to $k$ then the next bit will be equal to $0$, otherwise it will be equal to $1$ (in this case we need to reduce $k$ by this number before proceeding to the next level). The amount of pairs at most doubles when we go one level deeper, but in total we will encounter the same node at most twice in the pairs. The complexity of this algorithm is $O(62 \cdot n)$. Since the full trie likely won't fit into memory, so we will build it implicitly - first sort the values first and then represent trie node with a range of indices on the sorted array. This will not change the overall complexity of the solution.
|
[
"strings",
"trees"
] | 2,900
| null |
1055
|
G
|
Jellyfish Nightmare
|
Bob has put on some weight recently. In order to lose weight a bit, Bob has decided to swim regularly in the pool. However, the day before he went to the pool for the first time he had a weird dream. In this dream Bob was swimming along one of the pool's lanes, but also there were some jellyfish swimming around him. It's worth mentioning that jellyfish have always been one of Bob's deepest childhood fears.
Let us assume the following physical model for Bob's dream.
- The pool's lane is an area of the plane between lines $x=0$ and $x=w$. Bob is not allowed to swim outside of the lane, but he may touch its bounding lines if he wants.
- The jellyfish are very small, but in Bob's dream they are extremely swift. Each jellyfish has its area of activity around it. Those areas are circles of various radii, with the jellyfish sitting in their centers. The areas of activity of two jellyfish may overlap and one area of activity may even be fully contained within another one.
- Bob has a shape of a convex polygon.
- Unfortunately, Bob's excess weight has made him very clumsy, and as a result he can't rotate his body while swimming. So he swims in a parallel translation pattern. However at any given moment of time he can choose any direction of his movement.
- Whenever Bob swims into a jellyfish's activity area, it will immediately notice him and sting him very painfully. We assume that Bob has swum into the activity area if at some moment of time the intersection of his body with the jellyfish's activity area had a positive area (for example, if they only touch, the jellyfish does not notice Bob).
- Once a jellyfish stung Bob, it happily swims away and no longer poses any threat to Bob.
Bob wants to swim the lane to its end and get stung the least possible number of times. He will start swimming on the line $y=-h$, and finish on the line $y=h$ where $h = 10^{10}$.
|
First of all, we will solve a simpler problem: you need to check if it is possible for Bob to swim along the whole lane without any jellyfish stinging him. The position of Bob is identified by the location of his first vertex. Let's find out what are the prohibited areas for it. If a jellyfish had no activity zone and would only sting Bob only if he was swimming over it, the prohibited areas would look like polygons around every jellyfish. If we add the activity zone of radius $r$, prohibited areas will become "inflated" polygons. To be more precise, if the shape of Bob is a polygon $P$ they would have a shape of Minkowski sum of a polygon $-P$ with a circle of radius $r$. $-P$ here stands for the polygon inverted relative to the origin. Now, some of the areas will overlap and prohibit passing between two jellyfishes. If those two jellyfishes have activity areas of radii $r_1$ and $r_2$, centered at $(x_1, y_1)$ and $(x_2, y_2)$ respectively, Bob may not swim between them if the vector $(x_1 - x_2, y_1 - y_2)$ belongs to the Minkowski sum of $P$, $-P$ and a circle of radius $r_1 + r_2$. This may be checked by finding the distance from that vector to the polygon $P \oplus -P$ (here $\oplus$ stands for Minkowski sum) and comparing it with $r_1 + r_2$. One thing you need to note here is that at given constraints you can't do those computations in floating point numbers, because the relative difference between $r_1 + r_2$ and the distance from a vector to a polygon may be as low as $10^{-17}$. Therefore, you need to do all calculations in integers. Once you know pair of jellyfishes between which you cannot pass, you also need to find out if you are able to pass between the boundaries of the lane ($x=0$ and $x=w$) and the jellyfish. This allows you to construct a graph where every jellyfish and both boundaries are vertices, and the is an edge between two vertices if you cannot pass between them. One may notice that if the left boundary and right boundary are in the same connected component, then it's not possible for Bob to swim without being stung by any jellyfish. It's also possible to prove is that if they are not in the same component, then there is a safe path for Bob. Returning to the original problem, we may rephrase it like this: remove the least possible number of jellyfishes so that Bob can swim without being stung. This can be solved using min-cut by a standard trick of splitting every vertex corresponding to the jellyfish into two and adding an edge of capacity $1$ between them. The rest of the edges will have capacity $+\infty$, left boundary will be the source, and the right boundary will be the target.
|
[] | 3,500
| null |
1056
|
A
|
Determine Line
|
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.
During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
|
This is a simple implementation problem. A tram line is suitable if it appears at all stops, i.e. exactly $n$ times. Make an array of $100$ integers and count how many times each integer appears. Then just output each index where the array hits $n$.
|
[
"implementation"
] | 800
| null |
1056
|
B
|
Divide Candies
|
Arkady and his friends love playing checkers on an $n \times n$ field. The rows and the columns of the field are enumerated from $1$ to $n$.
The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set of candies per each cell of the field: the set of candies for cell $(i, j)$ will have exactly $(i^2 + j^2)$ candies of unique type.
There are $m$ friends who deserve the present. How many of these $n \times n$ sets of candies can be split equally into $m$ parts without cutting a candy into pieces? Note that each set has to be split independently since the types of candies in different sets are different.
|
We are asked to count the number of pairs $(i, j)$ so that $(i^2 + j^2) \bmod m = 0$. Note that $(i^2 + j^2) \bmod m = ((i \bmod m)^2 + (j \bmod m)^2) \bmod m$. Thus the answer is equal for all pairs $(i, j)$ that have equal values $(i \bmod m, j \bmod m) = (x, y)$. Let's loop through all possible pairs of $(x, y)$ (there are $m^2$ of them), check if $(x^2 + y^2) \bmod m = 0$ and if yes, add to the answer the number of suitable pairs $(i, j)$, that is easy to compute in $O(1)$. The complexity of the solution is $O(m^2)$.
|
[
"math",
"number theory"
] | 1,600
| null |
1056
|
C
|
Pick Heroes
|
\begin{quote}
Don't you tell me what you think that I can be
\end{quote}
If you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.
There are $2$ teams each having $n$ players and $2n$ heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.
The friends estimate the power of the $i$-th of the heroes as $p_i$. Each team wants to maximize the total power of its heroes. However, there is one exception: there are $m$ pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team \textbf{must} choose the other one on its turn. Each hero is in at most one such pair.
This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of $q$ or greater regardless of jury's program choices, you must get $q$ or greater to pass a test.
|
First suppose we have the first turn. Let's look at what total power we can grab. There are two types of heroes: those who have a special pair and those who don't. In each pair, one of the heroes will go into your team and one into the other. So the maximum we can get here is the sum of powers of the best in corresponding pairs heroes. Now consider only the heroes that don't have pairs. I claim that you and your opponent will pick heroes from this list alternating turns. Indeed, picking a "paired" hero doesn't change the turns order because the opponent will also pick a "paired" hero. From this point it is easy to see that the best you can get from "unpaired" heroes is the sum of powers of the first, the third, the fifth and so on heroes, if sorted in decreasing order of power. Now that we have proved the maximum constraint on our total power, let's build an algorithm that always reaches this power. If the first turn is ours, we have the initiative and the natural idea is not to lose it. Indeed, we can first pick all best "paired" heroes and then just keep picking the best remaining hero till the end. Since in the first part the opponent has to follow the rule about "paired" heroes, he won't be able to prevent us from taking the desired sum of power. If our turn is the second one, we don't have any option until all "paired" heroes are gone or the opponent gives the initiative back to us choosing an "unpaired" hero. Starting from this point we can use the same strategy as if we had the first turn. The solution can be implemented in linear time.
|
[
"greedy",
"implementation",
"interactive",
"sortings"
] | 1,700
| null |
1056
|
D
|
Decorate Apple Tree
|
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $1$ to $n$, the junction $1$ is called the root.
A subtree of a junction $v$ is a set of junctions $u$ such that the path from $u$ to the root must pass through $v$. Note that $v$ itself is included in a subtree of $v$.
A leaf is such a junction that its subtree contains exactly one junction.
The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction $t$ that all light bulbs in the subtree of $t$ have different colors.
Arkady is interested in the following question: for each $k$ from $1$ to $n$, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to $k$?
|
I'll try two describe two different approaches to this problem. A more intuitive solution. We are asked to output the number of colors for all $k$, let's reverse the problem and count the maximum $k$ for all possible number of colors $c$. We can see that if we a junction is happy then all junctions in its subtree are also happy. So we're interested in selecting some set of junctions so that their subtrees are disjoint and have no more than $c$ leaves, and we want to maximize the total size of these subtrees. This can be done greedily from the root: if a subtree is small enough, take it all, in the other case go to its children instead. We can see that a subtree is in the answer set for all $c$ not less than the size of the subtree and less than the size of the parent's subtree. We can easily compute this range for all junction in one deep-first search and sum the answer on these segments. A more professional solution. Note that a junction can be happy only when the number of colors is at least the number of leaves in it. The rule is that this is the only condition needed: indeed, if we color the leaves cyclically in the order of Euler tour, all such junctions will be happy. So the answer for the number of colors is simply the number of junctions that have at most $c$ leaves in the subtree Both solutions can be implemented in $O(n)$.
|
[
"constructive algorithms",
"dfs and similar",
"dp",
"graphs",
"greedy",
"sortings",
"trees"
] | 1,600
| null |
1056
|
E
|
Check Transcription
|
One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $s$ towards a faraway galaxy. Recently they've received a response $t$ which they believe to be a response from aliens! The scientists now want to check if the signal $t$ is similar to $s$.
The original signal $s$ was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal $t$, however, does not look as easy as $s$, but the scientists don't give up! They represented $t$ as a sequence of English letters and say that $t$ is similar to $s$ if you can replace all zeros in $s$ with some string $r_0$ and all ones in $s$ with some other string $r_1$ and obtain $t$. The strings $r_0$ and $r_1$ must be different and non-empty.
Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings $r_0$ and $r_1$) that transform $s$ to $t$.
|
The solution builds on one key observation. Suppose we know the length of $r_0$. Then, since the number of '0' and '1' is fixed and the length of the resulting string is also fixed, we know the length of $r_1$ (or know, that there is no integer-sized $r_1$ possible). So let's bruteforce the length of $r_0$, calculate the length of $r_1$ and then check whether the corresponding substrings of $t$ are equal (so $r_0$ and $r_1$ can be defined correctly). Sounds like $O(|s| |t|)$ (since the number of candidates is $\le |t|$ and check can be done in $|s|$, for example with hashes)? Haha, it is $O(|t|)$. First, notice that it is not exactly important whether we bruteforce length of $r_0$ or $r_1$ - one of them defines the other one. So suppose we are bruteforcing over the letter with larger number of occurrences in pattern string $s$. Let's denote it's number of occurrences as $c$, this way, clearly, there are at most $\frac{|t|}{c}$ candidates. And each candidate is checked in $|s|$. So the whole time is $\frac{|t|}{c} |s|$ Since we used the more frequent letter, $c \ge \frac{|s|}{2}$. And hence $\frac{|t|}{c} |s| \le 2|t|$.
|
[
"brute force",
"data structures",
"hashing",
"strings"
] | 2,100
| null |
1056
|
F
|
Write The Contest
|
Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of $n$ problems and lasts for $T$ minutes. Each of the problems is defined by two positive integers $a_i$ and $p_i$ — its difficulty and the score awarded by its solution.
Polycarp's experience suggests that his skill level is defined with positive real value $s$, and initially $s=1.0$. To solve the $i$-th problem Polycarp needs $a_i/s$ minutes.
Polycarp loves to watch series, and before solving each of the problems he will definitely watch one episode. After Polycarp watches an episode, his skill decreases by $10\%$, that is skill level $s$ decreases to $0.9s$. Each episode takes exactly $10$ minutes to watch. When Polycarp decides to solve some problem, he firstly has to watch one episode, and only then he starts solving the problem without breaks for $a_i/s$ minutes, where $s$ is his current skill level. In calculation of $a_i/s$ no rounding is performed, only division of integer value $a_i$ by real value $s$ happens.
Also, Polycarp can train for some time. If he trains for $t$ minutes, he increases his skill by $C \cdot t$, where $C$ is some given positive real constant. Polycarp can train only before solving any problem (and before watching series). Duration of the training can be arbitrary real value.
Polycarp is interested: what is the largest score he can get in the contest? It is allowed to solve problems in any order, while training is only allowed \textbf{before solving the first problem}.
|
Firstly, if we fix some set of problems to solve, it's always optimal to solve them from the hardest one to the easiest one. That implies a solution which processes all problems and decides which of them will be solved in sorted order. Secondly, suppose Polycarp doesn't train at all, and for some fixed set of $k$ problems it will take him $10k + m$ minutes, where $10k$ is the time spent on watching the series, and $m$ is the time spent on actually solving the problems. If Polycarp would raise his skill to $s$ before solving all the problems, then it would take him $10k + \frac{m}{s}$ minutes to solve the same set of problems in the same order. So if we fix a set of problems and compute $m$ for it, it's easy to see that if Polycarp trains for $t$ minutes, then it will take him $10k + \frac{m}{1 + Ct} + t$ minutes to train and solve all the problems. This function $f(t) = 10k + \frac{m}{1 + Ct} + t$ can be minimized with ternary search or some pen and paper work. This function also gives us the following: among two sets of problems with equal total score and equal number of problems it's optimal to choose the set having smaller value of $m$. So we can write a knapsack-like dynamic programming: $dp_{x, k}$ - the smallest possible value of $m$ for a set of $k$ problems with total score $x$. After computing these dynamic programming values, for a given pair $(x, k)$ it's easy to check if the time required to obtain this result does not exceed $T$: just minimize the function $f(t) = 10k + \frac{dp_{x, k}}{1 + Ct} + t$.
|
[
"binary search",
"dp",
"math"
] | 2,500
| null |
1056
|
G
|
Take Metro
|
Having problems with tram routes in the morning, Arkady decided to return home by metro. Fortunately for Arkady, there is only one metro line in the city.
Unfortunately for Arkady, the line is circular. It means that the stations are enumerated from $1$ to $n$ and there is a tunnel between any pair of consecutive stations as well as between the station $1$ and the station $n$. Trains that go in clockwise direction visit the stations in order $1 \to 2 \to 3 \to \ldots \to n \to 1$ while the trains that go in the counter-clockwise direction visit the stations in the reverse order.
The stations that have numbers from $1$ to $m$ have interior mostly in red colors while the stations that have numbers from $m + 1$ to $n$ have blue interior. Arkady entered the metro at station $s$ and decided to use the following algorithm to choose his way home.
- Initially he has a positive integer $t$ in his mind.
- If the current station has red interior, he takes a clockwise-directed train, otherwise he takes a counter-clockwise-directed train.
- He rides exactly $t$ stations on the train and leaves the train.
- He decreases $t$ by one. If $t$ is still positive, he returns to step $2$. Otherwise he exits the metro.
You have already realized that this algorithm most probably won't bring Arkady home. Find the station he will exit the metro at so that you can continue helping him.
|
There were a variety of approaches to this problem. In all of them you first have to note that there are only $n^2$ different positions describes as pairs (station, $T \bmod n$). Now if you manually perform several first steps to make $T \bmod n = 0$, you will have to perform $T / n$ large steps, each of them is to have $n$ rides with $T = n$, $T = n - 1$, ..., $T = 1$. If you compute for each station the station you will end up after a large step, you will get a functional graph where you will easily find the answer, computing a period and a pre-period. The question is how to get the graph. The first approach is to be strong and code a persistent treap (or any other persistent data structure that supports split and merge). This approach is $O(n \log(n))$. The second approach is... to rely that the cycle is not large and compute all large tests in a straightforward way. This also works fast, but we don't have a proof for that.
|
[
"brute force",
"data structures",
"graphs"
] | 2,900
| null |
1056
|
H
|
Detect Robots
|
You successfully found poor Arkady near the exit of the station you've perfectly predicted. You sent him home on a taxi and suddenly came up with a question.
There are $n$ crossroads in your city and several bidirectional roads connecting some of them. A taxi ride is a path from some crossroads to another one without passing the same crossroads twice. You have a collection of rides made by one driver and now you wonder if this driver can be a robot or they are definitely a human.
You think that the driver can be a robot if for every two crossroads $a$ and $b$ the driver always chooses the same path whenever he drives from $a$ to $b$. Note that $a$ and $b$ here do not have to be the endpoints of a ride and that the path from $b$ to $a$ can be different. On the contrary, if the driver ever has driven two different paths from $a$ to $b$, they are definitely a human.
Given the system of roads and the description of all rides available to you, determine if the driver can be a robot or not.
|
The solution is sqrt decomposition. Let's divide the rides into two groups: with length greater than $R$ and with length smaller than $R$. Now let's reformulate the problem a bit: for each pair of paths you have to check the following: for each $a$ and $b$ that appear in this order in both paths, the next crossroads after $a$ should be same in both paths. Now it's easy to check this condition for a pair of paths from the second set in a straightforward way. Now iterate through a path from the first set and any other set. Let's first the last common crossroads in the paths. Now when you iterate through all common points, it is easy to check the aforementioned condition. Choosing $R = O(\sqrt{n})$, the solution can be implemented in $O(n\sqrt{n})$.
|
[
"data structures",
"strings"
] | 3,200
| null |
1059
|
A
|
Cashier
|
Vasya has recently got a job as a cashier at a local store. His day at work is $L$ minutes long. Vasya has already memorized $n$ regular customers, the $i$-th of which comes after $t_{i}$ minutes after the beginning of the day, and his service consumes $l_{i}$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer.
Vasya is a bit lazy, so he likes taking smoke breaks for $a$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day?
|
There are only $n + 1$ possible segments of time when Vasya can take breaks: between the consecutive clients, before the first client, and after the last client. If the length of the $i$-th such segment is $s$, Vasya may take at most $\left \lfloor \frac{s}{a}\right\rfloor$ breaks, so we just sum those values over the $n + 1$ possible segments. Time complexity is $O(n)$.
|
[
"implementation"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int n, L, a;
int t[maxn], l[maxn];
int main(){
scanf("%d%d%d", &n, &L, &a);
for(int i = 0; i < n; i++){
scanf("%d%d", &t[i], &l[i]);
}
int start = 0;
int ans = 0;
for(int i = 0; i < n; i++){
ans += (t[i] - start)/a;
start = t[i] + l[i];
}
ans += (L - start)/a;
printf("%d", ans);
return 0;
}
|
1059
|
B
|
Forgery
|
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an $n\times m$ grid, where every cell is either filled with ink or empty. Andrey's pen can fill a $3\times3$ square without its central cell if it is completely contained inside the grid, as shown below.
\begin{center}
\begin{verbatim}
xxx
x.x
xxx
\end{verbatim}
\end{center}
Determine whether is it possible to forge the signature on an empty $n\times m$ grid.
|
Each empty cell forbids to put a pen into every neighbor. Also, the border of the grid is forbidden. Let's mark all the forbidden cells. Now we have to check if for each filled cell there is at least one non-forbidden neighbor. Time complexity is $O(nm)$.
|
[
"implementation"
] | 1,300
|
#include<bits/stdc++.h>
using namespace std;
const int maxn = (int)1e3 + 3;
int n, m;
char a[maxn][maxn];
bool can[maxn][maxn];
vector<int> must_have[maxn][maxn];
inline bool inside(int x, int y){
return x >= 0 && y >= 0 && x < n && y < m;
}
int main(){
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
can[i][j] = true;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++){
do{
a[i][j] = getc(stdin);
}while(a[i][j] != '.' && a[i][j] != '#');
for(int dx = -1; dx <= 1; dx++)
for(int dy = -1; dy <= 1; dy++){
if(abs(dx) + abs(dy) == 0 || !inside(i + dx, j + dy))continue;
if(a[i][j] == '.')can[i + dx][j + dy] = false;
else if (i + dx != 0 && j + dy != 0 && i + dx != n - 1 && j + dy != m - 1)must_have[i][j].push_back((i + dx) * m + j + dy);
}
}
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++){
bool good = false;
if(a[i][j] == '.')continue;
for(int cand : must_have[i][j]){
int x = cand/m, y = cand%m;
good |= can[x][y];
}
if(!good){printf("NO"); return 0;}
}
printf("YES");
return 0;
}
|
1059
|
C
|
Sequence Transformation
|
Let's call the following process a transformation of a sequence of length $n$.
If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $n$ integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence $1, 2, \dots, n$. Find the lexicographically maximum result of its transformation.
A sequence $a_1, a_2, \ldots, a_n$ is lexicographically larger than a sequence $b_1, b_2, \ldots, b_n$, if there is an index $i$ such that $a_j = b_j$ for all $j < i$, and $a_i > b_i$.
|
The answers for $n \le 3$ are given in the samples. Now suppose that $n \ge 4$. The maximum result must have the earliest appearance of an integer different from $1$. If $n \ge 4$, the earliest integer that may appear is $2$. So initially we must remove all odd integers and for each of them append $1$ to the answer. But now the rest of the answer is simply the answer for $\left\lfloor\frac{n}{2}\right\rfloor$ multiplied by $2$. That gives us an $O(n)$ solution.
|
[
"constructive algorithms",
"math"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 6;
int seq[maxn];
int ans[maxn];
int ptr = 0;
void solve(int n, int mul){
if(n == 1){ans[ptr++] = mul; return;}
if(n == 2){ans[ptr++] = mul; ans[ptr++] = mul * 2; return;}
if(n == 3){ans[ptr++] = mul; ans[ptr++] = mul; ans[ptr++] = mul * 3; return;}
for(int i = 0; i < n; i++)if(seq[i]&1)ans[ptr++] = mul;
for(int i = 0; i < n/2; i++)seq[i] = seq[2*i + 1]/2;
solve(n/2, mul * 2);
}
int main(){
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)seq[i] = i + 1;
solve(n, 1);
for(int i = 0; i < n; i++)printf("%d ", ans[i]);
return 0;
}
|
1059
|
D
|
Nature Reserve
|
There is a forest that we model as a plane and live $n$ rare animals. Animal number $i$ has its lair in the point $(x_{i}, y_{i})$. In order to protect them, a decision to build a nature reserve has been made.
The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.
For convenience, scientists have made a transformation of coordinates so that the river is defined by $y = 0$. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve.
|
If there are both positive and negative $y_i$, the answer is $-1$. Now assume that $y_i > 0$. Key observation: the answer can be binary searched. How to check if there is a valid circle with radius $R$? Firstly, the center of such circle is on the line $y = R$. Every point must be not farther than $R$ from the center. It means that the center is inside or on the boundary of all circles $(p_i, R)$. The intersection of every such circle with $y = R$ creates a segment (possibly empty). If the intersection of all such segments is non-empty, there exists some valid circle. Total complexity is $O(n\log C)$. There is also an $O(n\log n)$ solution, but it's much harder to implement.
|
[
"binary search",
"geometry",
"ternary search"
] | 2,200
|
#include<bits/stdc++.h>
using namespace std;
typedef long double dbl;
const dbl eps = 1e-9;
inline bool gt(const dbl & x, const dbl & y){
return x > y + eps;
}
inline bool lt(const dbl & x, const dbl & y){
return y > x + eps;
}
inline dbl safe_sqrt(const dbl & D){
return D < 0 ? 0 : sqrt(D);
}
struct pt{
dbl x, y;
pt(){}
pt(dbl a, dbl b):x(a), y(b){}
};
const int N = 1e5 + 5;
const int STEPS = 150;
int n;
pt p[N];
inline bool can(dbl R){
dbl l = -1e16 - 1, r = 1e16 + 1;
for(int i = 0; i < n; i++){
dbl b = -2 * p[i].x;
dbl c = p[i].x * p[i].x + p[i].y * p[i].y - 2 * p[i].y * R;
dbl D = b * b - 4 * c;
if(lt(D, 0))
return false;
D = safe_sqrt(D);
dbl x1 = p[i].x - D/2, x2 = p[i].x + D/2;
l = max(l, x1);
r = min(r, x2);
}
return !gt(l, r);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
bool has_positive = false, has_negative = false;
for(int i = 0; i < n; i++){
int x, y;
cin >> x >> y;
p[i] = pt(x, y);
if(y > 0)has_positive = true;
else has_negative = true;
}
if(has_positive && has_negative){
cout << -1 << endl;
return 0;
}
if(has_negative){
for(int i = 0; i < n; i++)
p[i].y = -p[i].y;
}
dbl L = 0, R = 1e16;
std::function<dbl(dbl, dbl)> get_mid;
if(can(1)){
R = 1;
get_mid = [](dbl l, dbl r){return (l + r)/2.0;};
}
else{
L = 1;
get_mid = [](dbl l, dbl r){return sqrt(l * r);};
}
for(int step = 0; step < STEPS; step++){
dbl mid = get_mid(L, R);
if(can(mid))
R = mid;
else
L = mid;
}
cout.precision(16);
cout << fixed << get_mid(L, R) << endl;
}
|
1059
|
E
|
Split the Tree
|
You are given a rooted tree on $n$ vertices, its root is the vertex number $1$. The $i$-th vertex contains a number $w_i$. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than $L$ vertices and the sum of integers $w_i$ on each path does not exceed $S$. Each vertex should belong to exactly one path.
A vertical path is a sequence of vertices $v_1, v_2, \ldots, v_k$ where $v_i$ ($i \ge 2$) is the parent of $v_{i - 1}$.
|
There are two solutions. Both of them find the answer for each subtree in dfs: firstly for children, then for the vertex itself. In both solutions, we firstly calculate for each vertex how far up a vertical path starting at this vertex may go. It can be done with binary lifting in $O(n\log n)$. Now let's describe the first solution. Let $dp_i$ be the answer for the subtree of the $i$-th vertex. Let $dp\_sum_i$ be the sum of $dp_j$ where $j$ is a child of $i$. Suppose we want to include the $i$-th vertex in the path starting at some vertex $j$. Let $\{v_k\}$ be the set of vertices on the path between $i$ and $j$. Then the answer for $i$ in this case equals $1 + \sum\limits_{v_k} (dp\_sum_{v_k} - dp_{v_k})$ (if we assume that initially $dp_i = 0$). So we need to calculate the minimum such value for all $j$ in the subtree of $i$, for which we can create a path from $j$ to $i$. Let's build a segment tree over the Euler tour of the tree. After processing vertex $i$, we add $dp\_sum_i - dp_i$ on the segment that corresponds to the subtree of $i$. If after processing the vertex there are some vertices in it's subtree, for which there can be a vertical path to $i$, but there cannot be a vertical path to $p_i$, we set the value at the corresponding position in the Euler tour to $\infty$. The second solution is much simpler. When calculating the answers, in case of tie let's choose the answer where the path going through the root of the subtree may go further. Then the answers can be updated greedily. Both solutions work in $O(n \log n)$.
|
[
"binary search",
"data structures",
"dp",
"greedy",
"trees"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
const int lg = 20;
const ll inf = 1e18;
int n, L;
ll S;
int w[maxn];
vector<int> down[maxn];
ll sum[maxn];
int up[maxn];
int h[maxn];
int p[maxn][lg];
int path[maxn];
inline ll get_sum(int v){
return v == -1 ? 0 : sum[v];
}
void preprocess(int v, int pr = -1){
sum[v] = get_sum(pr) + w[v];
p[v][0] = pr;
h[v] = pr == -1 ? 0 : (1 + h[pr]);
up[v] = v;
for(int i = 1; i < lg; i++)
p[v][i] = p[v][i - 1] == -1 ? -1 : p[p[v][i - 1]][i - 1];
int dist = L - 1;
for(int i = lg - 1; i >= 0; i--){
if(p[up[v]][i] == -1 || (1<<i) > dist)continue;
if(get_sum(v) - get_sum(p[up[v]][i]) + w[p[up[v]][i]] <= S){
dist -= 1<<i;
up[v] = p[up[v]][i];
}
}
for(int u : down[v]){
preprocess(u, v);
}
}
int solve(int v){
int ans = 0;
int best = -1;
for(int u : down[v]){
ans += solve(u);
if(path[u] == u)continue;
if(best == -1 || h[best] > h[path[u]])
best = path[u];
}
if(best == -1){
best = up[v];
++ans;
}
path[v] = best;
return ans;
}
int main(){
scanf("%d%d%lld", &n, &L, &S);
for(int i = 0; i < n; i++){
scanf("%d", &w[i]);
if(w[i] > S){printf("-1"); return 0;}
}
for(int i = 1; i < n; i++){
int j;
scanf("%d", &j);
down[--j].push_back(i);
}
preprocess(0);
printf("%d", solve(0));
}
|
1061
|
A
|
Coins
|
You have unlimited number of coins with values $1, 2, \ldots, n$. You want to select some set of coins having the total value of $S$.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum $S$?
|
Notice that using maximum value coin whenever possible will be always optimal. Hence, we can use $floor(S / n)$ coins of value $n$. Now, if $S \mod n$ is not equal to $0$, then we need to use one more coin of valuation $S \mod n$. Hence, our answer can be written as $ceil(S / n)$. Overall Complexity: $O(1)$
|
[
"greedy",
"implementation",
"math"
] | 800
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long s = sc.nextLong();
long ans = (s - 1) / n + 1;
System.out.print(ans);
}
}
|
1061
|
B
|
Views Matter
|
You came to the exhibition and one exhibit has drawn your attention. It consists of $n$ stacks of blocks, where the $i$-th stack consists of $a_i$ blocks resting on the surface.
The height of the exhibit is equal to $m$. Consequently, the number of blocks in each stack is less than or equal to $m$.
There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks.
Find the maximum number of blocks you can remove such that the views for both the cameras would not change.
Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is \textbf{no gravity} in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.
|
Let's sort the array in increasing order and find the minimum number of blocks $X$ required to retain the same top and right views. Then, the answer would be $\sum_{i=1}^{n} A_i - X$. For every $i$ from $1$ to $N$, we need to keep at least $1$ block for this stack to retain the top view. Thus, $X = X + 1$ for every $i$. However, we also need to maintain the maximum height we can cover till now, by keeping $1$ block in this stack. Let the previous best height we had be $Y$. Then, if $A[i] > Y$, then we managed to increase the height $Y$ by $1$, by keeping the block at $Y + 1$. However, if $A[i] = Y$, then we cannot increase the number of blocks in the right view, since we are only allowed to keep the current block in range $[1, Y]$. In the end, when we finish processing all the stacks, we also need to keep $max(A_i) - Y$ blocks in the longest stack, to retain the right view as it was originally. Overall complexity: $O(n \log n)$ Refer to solution code for clarity.
|
[
"greedy",
"implementation",
"sortings"
] | 1,400
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long totalBlocks = 0;
long a[] = new long[n];
for(int i = 0; i < n; ++i) {
a[i] = sc.nextLong();
totalBlocks += a[i];
}
Arrays.sort(a);
long selected = 0;
for(int i = 0; i < n; ++i) {
if(a[i] > selected)
selected++;
}
long leftCols = a[n - 1] - selected;
long remBlocks = totalBlocks - leftCols - n;
System.out.print(remBlocks);
}
}
|
1061
|
C
|
Multiplicity
|
You are given an integer array $a_1, a_2, \ldots, a_n$.
The array $b$ is called to be a subsequence of $a$ if it is possible to remove some elements from $a$ to get $b$.
Array $b_1, b_2, \ldots, b_k$ is called to be good if it is not empty and for every $i$ ($1 \le i \le k$) $b_i$ is divisible by $i$.
Find the number of good subsequences in $a$ modulo $10^9 + 7$.
Two subsequences are considered different if index sets of numbers included in them are different. That is, the values of the elements do not matter in the comparison of subsequences. In particular, the array $a$ has exactly $2^n - 1$ different subsequences (excluding an empty subsequence).
|
Let's introduce the following dynamic programming approach, $dp[n][n]$, where $dp[i][j]$ indicates the number of ways to select a good subsequence of size $j$ from elements $a_1, a_2, ..., a_i$. Our final answer will be $\sum_{i=1}^{n} dp[n][i]$. $dp[i][j] = \begin{cases} dp[i - 1][j] + dp[i - 1][j - 1] & \quad \text{if } a[i] \text{ is a multiple of } j\\ dp[i - 1][j] & \quad \text{otherwise} \end{cases}$ Now, maintaining a 2-D dp will exceed memory limit, however notice that $dp[i]$ is calculated only on the basis of $dp[i - 1]$, hence mainitaining a 1-D dp will work. Also, now $dp[j]$ is updated if and only if $j$ is a divisor of $a[i]$. We can find divisors of a number $x$ in $O(\sqrt{x})$. Overall Complexity : $O(n \cdot (maxD + \sqrt{maxA}))$. Here, $maxD$ indicates maximum number of divisors possible and $maxA$ indicates maximum value of $a_i$ possible. Also, we can use sieve to compute divisors of each number and achieve complexity of $O(maxA\cdot log(maxA) + n \cdot maxD)$.
|
[
"data structures",
"dp",
"implementation",
"math",
"number theory"
] | 1,700
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for(int i = 0; i < n; ++i)
a[i] = sc.nextInt();
int divCnt[] = new int[1000001];
for(int i = 1000000; i >= 1; --i) {
for(int j = i; j <= 1000000; j += i)
divCnt[j]++;
}
int div[][] = new int[1000001][];
for(int i = 1; i <= 1000000; ++i)
div[i] = new int[divCnt[i]];
int ptr[] = new int[1000001];
for(int i = 1000000; i >= 1; --i) {
for(int j = i; j <= 1000000; j += i)
div[j][ptr[j]++] = i;
}
long mod = (long)1e9 + 7;
long ans[] = new long[1000001];
ans[0] = 1;
for(int i = 0; i < n; ++i) {
for(int j : div[a[i]]) {
ans[j] = (ans[j] + ans[j - 1]) % mod;
}
}
long fans = 0;
for(int i = 1; i <= 1000000; ++i) {
fans = (fans + ans[i]) % mod;
}
System.out.print(fans);
}
}
|
1061
|
D
|
TV Shows
|
There are $n$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $i$-th of the shows is going from $l_i$-th to $r_i$-th minute, both ends inclusive.
You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $[l_i, r_i]$ and $[l_j, r_j]$ intersect, then shows $i$ and $j$ can't be watched simultaneously on one TV.
Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.
There is a TV Rental shop near you. It rents a TV for $x$ rupees, and charges $y$ ($y < x$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $[a; b]$ you will need to pay $x + y \cdot (b - a)$.
You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $10^9 + 7$.
|
Solution: Sort the TV shows on the basis of their starting time. Now, we start allocating TVs greedily to the shows. For any show $i$, we allocate a new TV only if there is no old TV where the show ends at $r_o$, such that $r_o < l_i$ and $(l_i - r_o) \cdot y <= x$. Also, if there are many such old TVs, then we use the TV where $r_o$ is maximum. Proof: Notice that there is a minimal cost of $\sum_{i=1}^{n} (r_i - l_i) \cdot y$, which will always be added. Hence, the optimal solution completely depends on the rent of new TV and the time wasted on old TVs. Now, lets try to prove that allocating an old TV with maximum $r_o$ is optimal. Suppose we are allocating a TV to show $i$. Let's consider two old TVs $o1$ and $o2$, such that $r_{o1} < r_{o2} < l_i$ and $(l_i - r_{o1}) \cdot y <= x$. In such a case, it is possible to allocate both the TVs to this show. For choosing which TV to be allocated let's consider the three possible cases: Case I: There is no show $j (j > i)$, such that $(l_j - r_{o2}) \cdot y <= x$. In this case, it would be better to allocate TV $o2$ to show $i$, since $(l_i - r_{o2}) \cdot y < (l_i - r_{o1}) \cdot y$. Hence, allocating TV $o2$ to show $i$ is optimal in this case. Case II: There are shows $j (j > i)$, such that $(l_j - r_{o2}) \cdot y <= x$; but there is no show $j (j > i)$, such that $(l_j - r_{o1}) \cdot y <= x$. In this case, if we allocate TV $o1$ to show $i$ and TV $o2$ to show $j$, then the cost will be $(l_j - r_{o2}) \cdot y + (l_i - r_{o1}) \cdot y$. And, if we allocate TV $o2$ to show $i$, then we need to buy a new TV for show $j$ and our cost will be $x +(l_i - r_{o2}) \cdot y$. Now, as $(l_j - r_{o1}) \cdot y > x$, $(l_j - r_{o2}) \cdot y + (l_i - r_{o1}) \cdot y > x +(l_i - r_{o2}) \cdot y$. Hence, allocating TV $o2$ instead of TV $o1$ to show $i$ is optimal in this case. Case III: There are shows $j (j > i)$, such that $(l_j - r_{o1}) \cdot y <= x$. In this case, if we allocate TV $o1$ to show $i$, cost will be $(l_i - r_{o1}) \cdot y + (l_j - r_{o2}) \cdot y$. If we allocate TV $o2$ to show $i$, cost will be $(l_i - r_{o2}) \cdot y + (l_j - r_{o1}) \cdot y$. Here, we can see that in both of the allocations, the cost is $(l_i + l_j - r_{o1} - r_{o2}) \cdot y$ and so any allocation is optimal here. Hence, we can see that if more than one old TVs are available, allocating the one with maximum $r_o$ is always optimal. Overall Complexity: $O(n \cdot \log n)$
|
[
"data structures",
"greedy",
"implementation",
"sortings"
] | 2,000
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long x = sc.nextLong();
long y = sc.nextLong();
Show show[] = new Show[n];
for(int i = 0; i < n; ++i)
show[i] = new Show(sc.nextLong(), sc.nextLong());
Arrays.sort(show, new Comparator<Show>() {
public int compare(Show s1, Show s2) {
if(s1.l > s2.l)
return 1;
if(s1.l < s2.l)
return -1;
return 0;
}
});
PriorityQueue<Long> queue = new PriorityQueue<>(new Comparator<Long>() {
public int compare(Long l1, Long l2) {
if(l1 < l2)
return -1;
if(l1 > l2)
return 1;
return 0;
}
});
long ans = 0;
Stack<Long> stack = new Stack<>();
for(int i = 0; i < n; ++i) {
long l = show[i].l;
long r = show[i].r;
while(queue.size() != 0 && queue.peek() < l)
stack.push(queue.poll());
if(stack.size() == 0) {
ans += x + (r - l) * y;
ans %= 1000000007;
}
else {
if((l - stack.peek()) * y < x) {
ans += (r - stack.pop()) * y;
ans %= 1000000007;
}
else {
ans += x + (r - l) * y;
ans %= 1000000007;
}
}
queue.add(r);
}
System.out.print(ans);
}
}
class Show {
long l, r;
Show(long a, long b) {
l = a;
r = b;
}
}
|
1061
|
E
|
Politics
|
There are $n$ cities in the country.
Two candidates are fighting for the post of the President. The elections are set in the future, and both candidates have already planned how they are going to connect the cities with roads. Both plans will connect all cities using $n - 1$ roads only. That is, each plan can be viewed as a tree. Both of the candidates had also specified their choice of the capital among $n$ cities ($x$ for the first candidate and $y$ for the second candidate), which may or may not be same.
Each city has a potential of building a port (one city can have at most one port). Building a port in $i$-th city brings $a_i$ amount of money. However, each candidate has his specific demands. The demands are of the form:
- $k$ $x$, which means that the candidate wants to build exactly $x$ ports in the subtree of the $k$-th city of his tree (the tree is rooted at the capital of his choice).
Find out the maximum revenue that can be gained while fulfilling all demands of both candidates, or print -1 if it is not possible to do.
It is additionally guaranteed, that each candidate has specified the port demands for the capital of his choice.
|
Let's create a graph with a source, sink and two layers. Let the left layer denote the nodes of tree $1$ and right layer denote the nodes of tree $2$. Let's denote $x_i$ as the demand of the $i^{th}$ node. For a demand $(k, x)$ in tree 1, we add an edge from source to node $k$ in the left layer with $cost = 0$ and $capacity = x - \sum x_j$, such that $j$ is not equal to $i$ and $j$ belongs to the subtree of $i$. Similarly for a demand $(k, x)$ in tree 2, we add an edge from node $k$ in the right layer to sink with $cost = 0$ and $capacity = x - \sum x_j$, such that $j$ is not equal to $i$ and $j$ belongs to the subtree of $i$. Now, for every node $i$, let $\text{col1}_i$ be the closest node to $i$, such that $i$ belongs to subtree of $\text{col1}_i$ and the demand of $\text{col1}_i$ in tree $1$ has been provided. Similarly $\text{col2}_i$ be the closest node to $i$, such that $i$ belongs to subtree of $\text{col2}_i$ and the demand of $\text{col2}_i$ in tree $2$ has been provided. For every node $i$, we add an edge from $\text{col}1_i$ in left layer to $\text{col2}_i$ in right layer with $capacity = 1$ and $cost = -a_i$. Now, when we run min cost max flow on this graph, our answer will be negative of the minimum cost obtained. Overall Complexity: $O(n^3)$ using MCMF with bellman ford; $O(n^2 \cdot \log n)$ using MCMF with Dijkstra.
|
[
"flows",
"graphs"
] | 2,600
|
import java.util.*;
import static java.lang.Math.*;
public class MainE {
static int dfs(int i, int par, int[] flow, int[] col, int curCol) {
if(req[i] != -1)
curCol = i;
col[i] = curCol;
int cost = 0;
for(int j : adj[i]) {
if(j != par)
cost += dfs(j, i, flow, col, curCol);
}
if(req[i] != -1) {
if(cost > req[i]) {
flag = 1;
}
flow[i] = req[i] - cost;
cost = req[i];
}
return cost;
}
static int flag = 0;
static ArrayList<Integer> adj[];
static int req[];
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int capital1 = sc.nextInt() - 1;
int capital2 = sc.nextInt() - 1;
int maxVal = 0;
int a[] = new int[n];
for(int i = 0; i < n; ++i) {
a[i] = sc.nextInt();
maxVal = max(maxVal, a[i]);
}
ArrayList<Integer> adj1[] = new ArrayList[n];
for(int i = 0; i < n; ++i)
adj1[i] = new ArrayList<>();
for(int i = 0; i < n - 1; ++i) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adj1[u].add(v);
adj1[v].add(u);
}
ArrayList<Integer> adj2[] = new ArrayList[n];
for(int i = 0; i < n; ++i)
adj2[i] = new ArrayList<>();
for(int i = 0; i < n - 1; ++i) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adj2[u].add(v);
adj2[v].add(u);
}
adj = new ArrayList[n];
for(int i = 0; i < n; ++i)
adj[i] = adj1[i];
req = new int[n];
int q = sc.nextInt();
Arrays.fill(req, -1);
for(int i = 0; i < q; ++i) {
int ind = sc.nextInt() - 1;
req[ind] = sc.nextInt();
}
int reqFlow1 = req[capital1];
int col[] = new int[n];
int flow[] = new int[n];
Arrays.fill(flow, 1000);
dfs(capital1, -1, flow, col, capital1);
if(flag == 1) {
System.out.print("-1");
return;
}
adj = new ArrayList[n];
for(int i = 0; i < n; ++i)
adj[i] = adj2[i];
req = new int[n];
q = sc.nextInt();
Arrays.fill(req, -1);
for(int i = 0; i < q; ++i) {
int ind = sc.nextInt() - 1;
req[ind] = sc.nextInt();
}
int reqFlow2 = req[capital2];
if(reqFlow1 != reqFlow2) {
System.out.print("-1");
return;
}
int col2[] = new int[n];
int flow2[] = new int[n];
Arrays.fill(flow2, 1000);
dfs(capital2, -1, flow2, col2, capital2);
if(flag == 1) {
System.out.print("-1");
return;
}
List<Edge>[] graph = createGraph(2 * n + 2);
int source = 0, sink = 2 * n + 1;
for(int i = 0; i < n; ++i) {
addEdge(graph, source, i + 1, flow[i], 0);
addEdge(graph, n + i + 1, sink, flow2[i], 0);
addEdge(graph, col[i] + 1, n + col2[i] + 1, 1, -a[i] + maxVal);
}
int[] ans = minCostFlow(graph, source, sink, n);
if(ans[0] != reqFlow1) {
System.out.print("-1");
return;
}
int fans = ans[1] - maxVal * reqFlow1;
fans = -fans;
System.out.print(fans);
}
static class Edge {
int to, f, cap, cost, rev;
Edge(int v, int cap, int cost, int rev) {
this.to = v;
this.cap = cap;
this.cost = cost;
this.rev = rev;
}
}
static List<Edge>[] createGraph(int n) {
List<Edge>[] graph = new List[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
static void addEdge(List<Edge>[] graph, int s, int t, int cap, int cost) {
graph[s].add(new Edge(t, cap, cost, graph[t].size()));
graph[t].add(new Edge(s, 0, -cost, graph[s].size() - 1));
}
static void bellmanFord(List<Edge>[] graph, int s, int[] dist) {
int n = graph.length;
Arrays.fill(dist, Integer.MAX_VALUE);
dist[s] = 0;
boolean[] inqueue = new boolean[n];
int[] q = new int[n];
int qt = 0;
q[qt++] = s;
for (int qh = 0; (qh - qt) % n != 0; qh++) {
int u = q[qh % n];
inqueue[u] = false;
for (int i = 0; i < graph[u].size(); i++) {
Edge e = graph[u].get(i);
if (e.cap <= e.f)
continue;
int v = e.to;
int ndist = dist[u] + e.cost;
if (dist[v] > ndist) {
dist[v] = ndist;
if (!inqueue[v]) {
inqueue[v] = true;
q[qt++ % n] = v;
}
}
}
}
}
static int[] minCostFlow(List<Edge>[] graph, int s, int t, int maxf) {
int n = graph.length;
int[] prio = new int[n];
int[] curflow = new int[n];
int[] prevedge = new int[n];
int[] prevnode = new int[n];
int[] pot = new int[n];
// bellmanFord invocation can be skipped if edges costs are non-negative
bellmanFord(graph, s, pot);
int flow = 0;
int flowCost = 0;
while (flow < maxf) {
PriorityQueue<Long> q = new PriorityQueue<>();
q.add((long) s);
Arrays.fill(prio, Integer.MAX_VALUE);
prio[s] = 0;
boolean[] finished = new boolean[n];
curflow[s] = Integer.MAX_VALUE;
while (!finished[t] && !q.isEmpty()) {
long cur = q.remove();
int u = (int) (cur & 0xFFFF_FFFFL);
int priou = (int) (cur >>> 32);
if (priou != prio[u])
continue;
finished[u] = true;
for (int i = 0; i < graph[u].size(); i++) {
Edge e = graph[u].get(i);
if (e.f >= e.cap)
continue;
int v = e.to;
int nprio = prio[u] + e.cost + pot[u] - pot[v];
if (prio[v] > nprio) {
prio[v] = nprio;
q.add(((long) nprio << 32) + v);
prevnode[v] = u;
prevedge[v] = i;
curflow[v] = Math.min(curflow[u], e.cap - e.f);
}
}
}
if (prio[t] == Integer.MAX_VALUE)
break;
for (int i = 0; i < n; i++)
if (finished[i])
pot[i] += prio[i] - prio[t];
int df = Math.min(curflow[t], maxf - flow);
flow += df;
for (int v = t; v != s; v = prevnode[v]) {
Edge e = graph[prevnode[v]].get(prevedge[v]);
e.f += df;
graph[v].get(e.rev).f -= df;
flowCost += df * e.cost;
}
}
return new int[]{flow, flowCost};
}
}
|
1061
|
F
|
Lost Root
|
The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect $k$-ary tree if each vertex is either a leaf (has no children) or has exactly $k$ children. Also, in perfect $k$-ary tree all leafs must have same depth.
For example, the picture below illustrates perfect binary tree with $15$ vertices:
There is a perfect $k$-ary tree with $n$ nodes. The nodes are labeled with distinct integers from $1$ to $n$, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree.
You are allowed to make at most $60 \cdot n$ queries of the following type:
- "? $a$ $b$ $c$", the query returns "Yes" if node with label $b$ lies on the path from $a$ to $c$ and "No" otherwise.
Both $a$ and $c$ are considered to be lying on the path from $a$ to $c$.
When you are ready to report the root of the tree, print
- "! $s$", where $s$ is the label of the root of the tree.
It is possible to report the root only once and this query is not counted towards limit of $60 \cdot n$ queries.
|
This solution had many randomized approaches, some with higher probability of passing and some with lower probability of passing. The author's solution (there exist better solutions with even lower probability of failure - comment yours below) is as follows: Part 1: Checking if a node is a leaf node: It can be done in $O(n)$ queries. Suppose candidate node is $X$ Generate a random node $Y (!=X)$ For all $Z$, if $Y$ $X$ $Z$ is $false$, then $X$ is a leaf node, otherwise is not. Part 2: Finding a leaf node: Generate a random node and check if it is a leaf node. Probability of getting a lead node is $>=0.5$. Higher the $K$, higher the probability. So we can find a leaf node in $O(20\cdot n)$ queries with failure probability $(1/2)^{20}$ Part 3: Generating a leaf node in other subtree of the actual root: Fix a random node (that is not the same as the leaf node, $L1$, that we found), check if it is a leaf node, and if it is a leaf node and check if $2h-1$ nodes separate Leaf $1$ and this current leaf. If yes, we have found two separate leaf nodes and the $2h-1$ candidate nodes for the root. We can use $O(40\cdot n)$ queries to ensure a failure probability of $(1/2)^{20}$ Finally: Instead of checking all of them separately in $2H\cdot N$, we can fix their order in $O(H^2)$ by finding each node's appropriate position by placing them incrementally. Let the initial path be $L1$ $L2$, then we add $X$ to get $L1$ $X$ $L2$. Now to find $Y$'s appropriate position, we check if it lies between $L1$, $X$ or $X$, $L2$. And so on. In the final order, the middle node would be the root.
|
[
"interactive",
"probabilities"
] | 2,400
|
import java.util.*;
public class Main {
static HashMap<Long, Boolean> map = new HashMap<>();
static long getHash(long a, long b, long c) {
return (long)(n + 1) * (long)(n + 1) * a + (long)(n + 1) * b + c;
}
static boolean check(int a, int b, int c) {
long hashV = getHash(a, b, c);
if(map.get(hashV) != null)
return map.get(hashV);
// b in path a -> c
System.out.println("? " + a + " " + b + " " + c);
System.out.flush();
String s = sc.next();
map.put(hashV, s.equals("Yes"));
return map.get(hashV);
}
static int findHeight(int x) {
int nodes = 0;
int anotherNode = rand.nextInt(n) + 1;
while(anotherNode == x)
anotherNode = rand.nextInt(n) + 1;
for(int i = 1; i <= n; ++i) {
if(check(anotherNode, x, i))
nodes++;
}
if(level.get(nodes) == null)
return level.get(n - nodes) + 1;
else
return level.get(nodes);
}
static int findDist(int a, int b) {
int ans = 0;
for(int i = 1; i <= n; ++i) {
if(check(a, i, b))
ans++;
}
return ans;
}
static void printAns(int ans) {
System.out.println("! " + ans);
System.out.flush();
}
static int findLCA(int a, int b) {
ArrayList<Integer> list = new ArrayList<>();
for(int i = 1; i <= n; ++i) {
if(i == a || i == b)
continue;
if(check(a, i, b))
list.add(i);
}
ArrayList<Integer> path = new ArrayList<>();
path.add(a);
int vis[] = new int[list.size()];
for(int i = 0; i < list.size(); ++i) {
int selectedInd = -1;
for(int j = 0; j < list.size(); ++j) {
if(vis[j] == 0) {
if(selectedInd == -1)
selectedInd = j;
else if(check(a, list.get(j), list.get(selectedInd)))
selectedInd = j;
}
}
path.add(list.get(selectedInd));
vis[selectedInd] = 1;
}
int rootInd = height - height1;
return path.get(rootInd);
}
static int n, k;
static HashMap<Integer, Integer> level;
static int height, height1;
static Random rand;
static Scanner sc;
public static void main(String args[]) {
sc = new Scanner(System.in);
rand = new Random();
n = sc.nextInt();
k = sc.nextInt();
if(n == 1) {
printAns(1);
return;
}
height = 0;
int remNodes = n * k - n + 1;
while(remNodes != 1) {
height++;
remNodes /= k;
}
int nodes[] = new int[height + 1];
nodes[1] = 1;
level = new HashMap<>();
level.put(1, 1);
for(int i = 2; i <= height; ++i) {
nodes[i] = k * nodes[i - 1] + 1;
level.put(nodes[i], i);
}
int node1 = rand.nextInt(n) + 1;
height1 = findHeight(node1);
if(height1 == height) {
printAns(node1);
return;
}
HashSet<Integer> alrSet = new HashSet<>();
alrSet.add(node1);
int node2 = -1;
while(true) {
node2 = rand.nextInt(n) + 1;
while(alrSet.contains(node2))
node2 = rand.nextInt(n) + 1;
alrSet.add(node2);
int height2 = findHeight(node2);
if(height2 == height) {
printAns(node2);
return;
}
int dist = findDist(node1, node2);
if(height1 + height2 + dist - 2 == 2 * height - 1)
break;
}
int fans = findLCA(node1, node2);
printAns(fans);
}
}
|
1062
|
A
|
A Prank
|
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array $a_1$, $a_2$, ..., $a_n$ of integers, such that $1 \le a_1 < a_2 < \ldots < a_n \le 10^3$, and then went to the bathroom.
JATC decided to prank his friend by erasing some \textbf{consecutive elements} in the array. Since he doesn't want for the prank to go too far, he will only erase in a way, such that Giraffe can still restore the array using the information from the remaining elements. Because Giraffe has created the array, he's \textbf{also aware} that it's an increasing array and all the elements are integers in the range $[1, 10^3]$.
JATC wonders what is the greatest number of elements he can erase?
|
Since $1 \le a_i \le 10^3$ for all $i$, let set $a_0=0$ and $a_{n+1}=1001$. For every $i,j$ such that $0 \le i<j \le n+1$, if $a_j-j=a_i-i$ then we can erase all the elements between $i$ and $j$ (not inclusive). So just check for all the valid pairs and maximize the answer. Time complexity: $O(n^2)$.
|
[
"greedy",
"implementation"
] | 1,300
| null |
1062
|
B
|
Math
|
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer $n$, you can perform the following operations zero or more times:
- mul $x$: multiplies $n$ by $x$ (where $x$ is an arbitrary positive integer).
- sqrt: replaces $n$ with $\sqrt{n}$ (to apply this operation, $\sqrt{n}$ must be an integer).
You can perform these operations as many times as you like. What is the minimum value of $n$, that can be achieved and what is the minimum number of operations, to achieve that minimum value?
Apparently, no one in the class knows the answer to this problem, maybe you can help them?
|
By factorizing $n$ we get $n={p_1}^{a_1}{p_2}^{a_2}\dots{p_k}^{a_k}$ ($k$ is the number of prime factors). Because we can't get rid of those prime factors then the smallest $n$ is ${p_1}{p_2}\dots{p_k}$. For each $a_i$, let $u_i$ be the positive integer so that $2^{u_i} \ge a_i>2^{u_i-1}$. Let $U$ be $max(u_i)$. It's clear that we have to apply the "$sqrt$" operation at least $U$ times, since each time we apply it, $a_i$ is divided by $2$ for all $i$. If for all $i$, $a_i=2^U$ then the answer is $U$, obviously. Otherwise, we need to use the operation "$mul$" $1$ time to make all the $a_i$ equal $2^U$ and by now the answer is $U+1$. Complexity: $O(sqrt(N))$
|
[
"greedy",
"math",
"number theory"
] | 1,500
| null |
1062
|
C
|
Banh-mi
|
JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into $n$ parts, places them on a row and numbers them from $1$ through $n$. For each part $i$, he defines the deliciousness of the part as $x_i \in \{0, 1\}$. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the $i$-th part then his enjoyment of the Banh-mi will increase by $x_i$ and the deliciousness of all the remaining parts will also increase by $x_i$. The initial enjoyment of JATC is equal to $0$.
For example, suppose the deliciousness of $3$ parts are $[0, 1, 0]$. If JATC eats the second part then his enjoyment will become $1$ and the deliciousness of remaining parts will become $[1, \_, 1]$. Next, if he eats the first part then his enjoyment will become $2$ and the remaining parts will become $[\_, \_, 2]$. After eating the last part, JATC's enjoyment will become $4$.
However, JATC doesn't want to eat all the parts but to save some for later. He gives you $q$ queries, each of them consisting of two integers $l_i$ and $r_i$. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range $[l_i, r_i]$ in some order.
All the queries are independent of each other. Since the answer to the query could be very large, print it modulo $10^9+7$.
|
For each part that we choose, we need to calculate how many times that element is added to our score. You can see that, the first element that we choose is added $2^{k-1}$ times in our score ($k=r-l+1$), the second element is added $2^{k-2}$ times and so on. Therefore, we just need to choose all the $1s$ first and then all the remaining parts. The final score is $(2^x-1) \cdot 2^y$, where $x$ is the number of $1s$ and $y$ is the number of $0s$. Complexity: $O(n + Q)$.
|
[
"greedy",
"implementation",
"math"
] | 1,600
| null |
1062
|
D
|
Fun with Integers
|
You are given a positive integer $n$ greater or equal to $2$. For every pair of integers $a$ and $b$ ($2 \le |a|, |b| \le n$), you can transform $a$ into $b$ if and only if there exists an integer $x$ such that $1 < |x|$ and ($a \cdot x = b$ or $b \cdot x = a$), where $|x|$ denotes the absolute value of $x$.
After such a transformation, your score increases by $|x|$ points and you are \textbf{not allowed} to transform $a$ into $b$ nor $b$ into $a$ anymore.
Initially, you have a score of $0$. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?
|
For every integer $x$ $(1 \le x \le n)$, let's call $D$ the set of integers that are able to be transformed into $x$. As you can see, if $a$ could be transformed into $b$ then $-a$ could also be transformed into $b$. Therefore $|D|$ is always even. Let's build a graph consists of $2n-2$ nodes, numbered $-n$ through $n$ (except for $-1$, $0$, and $1$). There is an weighted undirected edge between node $u$ and $v$ if and only if $u$ can be transformed into $v$. The weight of the edge is the score of the transformation. Every node in the graph has an even degree so you can split the graph into some connected components so that each components is an Euler circuit (a circuit that contains all the edges). Therefore you just need to find all those Euler circuits and maximize your score. Moreover, you can see that, if an integer $a$ can be transformed into $b$ then $x$ and $2$ are in the same component. Proof: Suppose $a<b$, there exists an integer $x=b/a$. If $x=2$ then it is proved, otherwise there exists an integer $c=2x<b \le n$. $c$ and $2$ are in the same component so $x$ and $2$ are also in the same component. Therefore, if we ignore all the nodes that have no edges attached to it, the graph will be connected. So you need to simply get the sum of all the weights of the edges. The complexity is $O(n + nlog(n))$ since the number of edges can go up to $nlog(n)$.
|
[
"dfs and similar",
"graphs",
"implementation",
"math"
] | 1,800
| null |
1062
|
E
|
Company
|
The company $X$ has $n$ employees numbered from $1$ through $n$. Each employee $u$ has a direct boss $p_u$ ($1 \le p_u \le n$), except for the employee $1$ who has no boss. It is guaranteed, that values $p_i$ form a tree. Employee $u$ is said to be in charge of employee $v$ if $u$ is the direct boss of $v$ or there is an employee $w$ such that $w$ is in charge of $v$ and $u$ is the direct boss of $w$. Also, any employee is considered to be in charge of himself.
In addition, for each employee $u$ we define it's level $lv(u)$ as follow:
- $lv(1)=0$
- $lv(u)=lv(p_u)+1$ for $u \neq 1$
In the near future, there are $q$ possible plans for the company to operate. The $i$-th plan consists of two integers $l_i$ and $r_i$, meaning that all the employees in the range $[l_i, r_i]$, and only they, are involved in this plan. To operate the plan smoothly, there must be a project manager who is an employee in charge of \textbf{all} the involved employees. To be precise, if an employee $u$ is chosen as the project manager for the $i$-th plan then for every employee $v \in [l_i, r_i]$, $u$ must be in charge of $v$. Note, that $u$ is not necessary in the range $[l_i, r_i]$. Also, $u$ is always chosen in such a way that $lv(u)$ is as large as possible (the higher the level is, the lower the salary that the company has to pay the employee).
Before any plan is operated, the company has JATC take a look at their plans. After a glance, he tells the company that for every plan, it's possible to reduce the number of the involved employees \textbf{exactly} by one without affecting the plan. Being greedy, the company asks JATC which employee they should kick out of the plan so that the level of the project manager required is as large as possible. JATC has already figured out the answer and challenges you to do the same.
|
Let's call $in_u$ the time that we reach the node $u$ in depth first search and $out_u=max(in_{v1}, in_{v2}, \cdots, in_{vk})$ where $v_i$ is a child of $u$. If node $u$ is in charge of node $v$ ($u$ is an ancestor of $v$) then $in_u \le in_v \le out_u$. Suppose we don't have to ignore any node then the answer to each query is the LCA of two nodes $u$ and $v$ ($l \le u,v \le r$), where $u$ and $v$ are chosen so that $in_u=max(in_l, in_{l+1}, \dots, in_r)$ and $in_v=min(in_l,in_{l+1}, \dots, in_r)$. Proof: Let $r$ be the LCA of $u$ and $v$, then $in_r \le in_v \le in_u \le out_r$. For every node $w \in [l,r]$, $in_v \le in_w \le in_u \Rightarrow in_r \le in_w \le out_r \Rightarrow r$ is an ancestor of $w$. Therefore, the node that needs to be ignored is either $u$ or $v$. Suppose we ignore $u$, the query splits into two halves $[l,u-1] \cup [u+1,r]$. We find the LCA to each half and get the LCA of them. We do similarly for $v$ and optimize the answer. Complexity: $O(Nlog(N) + Qlog(N))$.
|
[
"binary search",
"data structures",
"dfs and similar",
"greedy",
"trees"
] | 2,300
| null |
1062
|
F
|
Upgrading Cities
|
There are $n$ cities in the kingdom $X$, numbered from $1$ through $n$. People travel between cities by some \textbf{one-way} roads. As a passenger, JATC finds it weird that from any city $u$, he can't start a trip in it and then return back to it using the roads of the kingdom. That is, the kingdom can be viewed as an acyclic graph.
Being annoyed by the traveling system, JATC decides to meet the king and ask him to do something. In response, the king says that he will upgrade some cities to make it easier to travel. Because of the budget, the king will only upgrade those cities that are important or semi-important. A city $u$ is called important if for every city $v \neq u$, there is either a path from $u$ to $v$ or a path from $v$ to $u$. A city $u$ is called semi-important if it is not important and we can destroy exactly one city $v \neq u$ so that $u$ becomes important.
The king will start to act as soon as he finds out all those cities. Please help him to speed up the process.
|
The main idea of this problem is to calculate $in_u$ and $out_u$ for every node $u$, where $in_u$ denotes the number of nodes that can reach $u$ and $out_u$ denotes the number of nodes that can be reached by $u$. If $in_u+out_u=N+1$ then $u$ is important or $N$ if $u$ is semi-important. However, it may not possible to calculate $in_u$ and $out_u$ for every node $u$ in given time (please tell me if it's possible) so we have to do some tricks. First of all, we need to find an arbitrary longest path ($P$)$=s_1 \rightarrow s_2 \rightarrow... \rightarrow s_k$ on the graph ($k$ is the number of nodes on this path). If a node is important then it must lie on this path ($1$). Proof: Assume there is a node $u$ that is important and doesn't lie on ($P$). Let $s_i$ be the rightmost node on ($P$) and can reach $u$. It's true that $i < k$, because if $i=k$ then we have a longer path than the one we found so it's not possible. By definition of $i$, $s_{i+1}$ cannot reach $u$. Therefore $u$ must be able to reach $s_{i+1}$ (because $u$ is important). This leads to a conflict: We have a path that is longer than the one we found: $s_1 \rightarrow s_2 \rightarrow \dots \rightarrow s_i \rightarrow u \rightarrow s_{i+1} \rightarrow \dots \rightarrow s_k$. Therefore statement ($1$) is proved. It takes $O(N+M)$ to find ($P$). Let's deal with important nodes first. Because all important nodes lie on the path ($P$) so it makes no sense to calculate $in$ and $out$ for those nodes that don't belong to ($P$). We can calculate $out$ by iterate through $P$ from $s_k$ to $s_1$. At each node $s_i$, we just need to use bfs or dfs to search for the nodes that can be reached by $s_i$. Because we visit each node $1$ time then it takes $O(N+M)$ to do this. To calculate $in$ we just need to reverse the direction of the edges and do similarly. Now we need to find the semi nodes. There are two types of semi nodes: those belong to ($P$) and those don't. For the ones belong to ($P$), we just need to check if $in_u+out_u=N$. For the ones don't belong to ($P$), suppose we are dealing with node $u$. Let $s_i$ be the rightmost node on ($P$) that can reach $u$ and $s_j$ be the leftmost node on ($P$) that can be reached by $u$. It's obvious that $i<j-1$. Let $L_u=i$ and $R_u=j$, let $leng$ equal $j-i-1$. If $leng>1$ then u is not a semi node (because we have to delete all nodes between i and j not inclusive), or else we must erase $s_{i+1}$ to make $u$ a semi important node. We can see that the path from $s_i$ to $u$ contains only $s_i$ and $u$, and the path from $u$ to $s_j$ contains only $u$ and $s_j$, because otherwise there exists a longer path than ($P$), which is false. So we consider $u$ as a candidate. Moreover, if exists a node $v$ that is a candidate and $L_u=L_v$ (also leads to $R_u=R_v$) then both $u$ and $v$ are not semi important nodes. Proof: After we delete $s_{i+1}$, for $u$, exists a path that is as long as ($P$) and does not go through $u$ (it goes through $v$) so $u$ is not a important node, based on statement ($1$). Same for $v$. Briefly, at this point we have the path ($P$) and a list of nodes $u_1, u_2, ..., u_t$. For every $i$, $u_i$ is a candidate and $L_{ui}+1=R_{ui}-1$. For every $i$, $j$, $L_{ui}!=L_{uj}$. So now we are going to calculate $in$ and $out$ for those candidate nodes. We can do this similarly as when we find the important nodes. To calculate $out$, iterate through $s_k$ to $s_1$. At each node $s_i$, bfs or dfs to search for nodes that can be reached by $s_i$. Additionally, if there is a candidate node $v$ that $R_v=i-1$, we start a search from $v$ to find those nodes that can be reached by $v$, we have $out_v=out_{si}+$ the number of nodes we just found. After that we pop those nodes from the stack (or whatever), mark them as not visited and continue to iterate to $s_{i-1}$. To calculate $in$ we reverse the directs of the edges and do the same. Because each node is visited $1$ time by nodes on ($P$) and at most $2$ times by candidate nodes so it takes $O(3(N+M))$. The total complexity is $O(N+M)$.
|
[
"dfs and similar",
"graphs"
] | 2,900
| null |
1063
|
A
|
Oh Those Palindromes
|
A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.
A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.
Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is $6$ because all its substrings are palindromes, and the palindromic count of the string "abc" is $3$ because only its substrings of length $1$ are palindromes.
You are given a string $s$. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.
|
One possible solution is just to sort the string. Why so? Note that each palindrome have equal character at their ends. Suppose this character is $c$ with $x$ number of occurences. Then there are at most $x(x + 1)/2$ palindromes with this character. So we have a clear upper bound on answer. It is easy to see, that the sorted string fulfills that bound and hence it is the optimal answer.
|
[
"constructive algorithms",
"strings"
] | 1,300
| null |
1063
|
B
|
Labyrinth
|
You are playing some computer game. One of its levels puts you in a maze consisting of $n$ lines, each of which contains $m$ cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row $r$ and column $c$. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.
Unfortunately, your keyboard is about to break, so you can move left no more than $x$ times and move right no more than $y$ times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.
Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
|
Suppose we started in cell $(i_{0}, j_{0})$ and examining whether we can reach cell $(i_{1}, j_{1})$. Let's denote the number of taken moves to the right as $R$ and number of moves to the left as $L$ Clearly, $j_{0} + R - L = j_{1}$ That is, $R - L = j_{1} - j_{0} = const$. Or, put otherwise $R = L + const$, where $const$ only depends on the starting cell and the target cell. So in fact we just need to minimize any of the left or right moves - the other one will be optimal as well. To calculate the minimum possible number of L-moves to reach some cell we can use 0-1 bfs. Solution is $O(nm)$.
|
[
"graphs",
"shortest paths"
] | 1,800
| null |
1063
|
C
|
Dwarves, Hats and Extrasensory Abilities
|
\textbf{This is an interactive problem.}
In good old times dwarves tried to develop extrasensory abilities:
- Exactly $n$ dwarves entered completely dark cave.
- Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves.
- Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information.
- The task for dwarves was to got diverged into two parts — one with dwarves with white hats and one with black hats.
After many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?
You are asked to successively name $n$ different integer points on the plane. After naming each new point you will be given its color — black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.
In this problem, the interactor is adaptive — the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output.
|
The solution is just.. binary search! We will use just a single line to put our points on. Let's maintain an invariant that all white colored points are on the left and all black colored on the right. Put a new point in the middle of the gap between white points and black points. Depending on the color said by jury shrink the gap to the left or to the right. In the end draw a diagonal line between white points and black points. The initializing binary search may look complicated but it isn't. Put a first point on the leftmost ($x = 0$) position, suppose that this point is white (if it is black just revert all colors), and then play as if there is a white point in $x = 0$ and black point in $x = 10^{9}$.
|
[
"binary search",
"constructive algorithms",
"geometry",
"interactive"
] | 1,900
| null |
1063
|
D
|
Candies for Children
|
At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly $k$ candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends in the circle. Lena knows, that some of her friends have a sweet tooth and others do not. Sweet tooth takes out of the box two candies, if the box has at least two candies, and otherwise takes one. The rest of Lena's friends always take exactly one candy from the box.
Before starting to give candies, Lena step out of the circle, after that there were exactly $n$ people remaining there. Lena numbered her friends in a clockwise order with positive integers starting with $1$ in such a way that index $1$ was assigned to her best friend Roma.
Initially, Lena gave the box to the friend with number $l$, after that each friend (starting from friend number $l$) took candies from the box and passed the box to the next friend in clockwise order. The process ended with the friend number $r$ taking the last candy (or two, who knows) and the empty box. Please note that it is possible that some of Lena's friends took candy from the box several times, that is, the box could have gone several full circles before becoming empty.
Lena does not know which of her friends have a sweet tooth, but she is interested in the maximum possible number of friends that can have a sweet tooth. If the situation could not happen, and Lena have been proved wrong in her observations, please tell her about this.
|
Solution works in $min(n^2, k / n)$ time. Also I will drop the case about the last person being sweet tooth and eating one candy instead of two. This adds few more cases but the idea stays the same. Basically in the formulas below just few $-1$ will appear, however there must be condition that there is at least one sweet tooth in corresponding part of the circle. So how to solve problem in $n^2$? Note, that basically we have two parts of the circle - the part between $[l; r]$ which get's candies one times more than the rest and the other one. Since we don't care about absolute values we can only worry about the lengths of this parts, let's denote them as $x$ and $y$. To solve in $n^2$ let's bruteforce the number of sweet tooth on first part ($a$) and the number of sweet tooth on the second part ($b$). Suppose that there were full $t$ loops. This way the number of eaten candies is $a * 2 * (t + 1) + (x - a) * 1 * (t + 1) + b * 2 * t + (y - b) * 1 * t$. This should be equal to $k$. Since we just bruteforced the values of $a$ and $b$ we now just have linear equation. If it is solvable, consider relaxing answer with $a + b$. How to solve problem in $k / n$? So as the asymptotic suggests the amount of turns $\le k / n$, so we can bruteforce it instead. Also it is worthy to handle case of $0$ turns specifically here since it produces some unpleasant effects otherwise. So each person in "$x$" part of the circle eats candies $t + 1$ times (so each person contributes $t + 1$ or $2t + 2$) and the other persons have eaten candies $t$ times (so each person contributes $t$ or $2t$). Let's account all persons as if they are not sweet tooths. So now each person in $x$ contributes $0$ or $t + 1$ and each person in $y$ contributes $0$ or $t$. So we basically have $(t + 1) a + t b = \gamma$. A Diophantine equation. Careful analysis or bits of theory suggest that the solutions are $a = a_0 - t z$, $b = b_0 + (t + 1) z$, for all integer $z$. Where $a_0$ and $b_0$ some arbitrary solutions which we can get with formulas. Also we need to have $0 \le a \le x$, $0 \le b \le y$, and the $a + b \to max$. These bounds imply that $t$ takes values only in some range $[t_1; t_2]$. Since the $a + b$ is linear function we can only consider $t_1$ and $t_2$ while searching for maximum $a + b$.
|
[
"brute force",
"math"
] | 2,600
| null |
1063
|
E
|
Lasers and Mirrors
|
Oleg came to see the maze of mirrors. The maze is a $n$ by $n$ room in which each cell is either empty or contains a mirror connecting opposite corners of this cell. Mirrors in this maze reflect light in a perfect way, which causes the interesting visual effects and contributes to the loss of orientation in the maze.
Oleg is a person of curious nature, so he decided to install $n$ lasers facing internal of the maze on the south wall of the maze. On the north wall of the maze, Oleg installed $n$ receivers, also facing internal of the maze. Let's number lasers and receivers from west to east with distinct integers from $1$ to $n$. Each laser sends a beam of some specific kind and receiver with number $a_i$ should receive the beam sent from laser number $i$. Since two lasers' beams can't come to the same receiver, these numbers form a permutation — each of the receiver numbers occurs exactly once.
You came to the maze together with Oleg. Help him to place the mirrors in the initially empty maze so that the maximum number of lasers' beams will come to the receivers they should. There are no mirrors outside the maze, so if the laser beam leaves the maze, it will not be able to go back.
|
The answer is always $n$ (if the permutation is identity) lasers or $n - 1$ (otherwise). Clearly, we can't have more than $n - 1$ matching lasers if the permutation is not identity. Consider just the very first line with mirrors. If the first mirror in this line is <<\>> then we miss the laser below this mirror, if the very last mirror is <</>> we miss the laser below it. Otherwise there are neighbouring <</>> and <<\>> and we lost two lasers now. The proof of $n - 1$ is constructive one. Ignore all fixed points in permutation (all $x$, that $p_x = x$). Select arbitrary cycle and select one point in it as <<dead>>. We can spend $|cycle| - 1$ operations to fix all points in this cycle. But we also need to fix all other cycles. We can do it in $|cycle| + 1$ operations: move arbitrary beam to the wasted laser, fix all other points and move that point back. But this is a bit too much lines. The trick is that we can perform movement of arbitrary beam to the wasted point and the first operation of fixing in just one line, if we select as the trash beam the rightmost point. See the following picture for an example (trash beam is the rightmost column):
|
[
"constructive algorithms",
"math"
] | 3,000
| null |
1063
|
F
|
String Journey
|
We call a sequence of strings $t_{1}, ..., t_{k}$ a journey of length $k$, if for each $i > 1$ $t_{i}$ is a substring of $t_{i - 1}$ and length of $t_{i}$ is strictly less than length of $t_{i - 1}$. For example, ${ab, b}$ is a journey, but ${ab, c}$ and ${a, a}$ are not.
Define a journey on string $s$ as journey $t_{1}, ..., t_{k}$, such that all its parts can be nested inside $s$ in such a way that there exists a sequence of strings $u_{1}, ..., u_{k + 1}$ (each of these strings can be empty) and $s = u_{1} t_{1} u_{2} t_{2}... u_{k} t_{k} u_{k + 1}$. As an example, ${ab, b}$ is a journey on string $abb$, but not on $bab$ because the journey strings $t_{i}$ should appear from the left to the right.
The length of a journey on a string is the number of strings in it. Determine the maximum possible length of a journey on the given string $s$.
|
This problem required quite a lot of nice observations! Observation 1. We can only consider journeys in which neighboring strings differ exactly by removing one symbol. All other journeys can be modified a bit to match the criterion above. Observation 2. If it is possible to start a journey at the symbol $i$ with lengths of strings $k$, $k - 1$, ..., $1$, it is always possible to start a journey at the same symbol $i$ with lengths $t$, $t - 1$, ..., $1$, given that $t \le k$. This suggests doing dynamic programming: $dp[i]$ is the maximum possible $k$ such that there is a journey starting at position $i$ of $k$ strings with lengths $k$, ..., $1$. Due to observation $1$ we only care about maximum - if we know maximum, we also known that all lesser values are also OK. So let's calculate this dynamic programming from right to left. How to check whether $dp[i] \ge k$ (given that tool, we can just use binary search for example)? There must be such $j$, that $j \ge i + k$, $dp[j] \ge k - 1$ and string $s_{j}, ..., s_{j + k - 2}$ must be a substring of string $s_{i}s_{i + 1}... s_{i + k - 1}$ (basically just two cases "left substring" or "right substring"). This almost gives us a solution, but we need few more observations to have $O(n\log n)$, and not $O(n\log^{e}n)$. Observation 3. If $dp[i] = k$, then $dp[i + 1] \ge k - 1$. We can use this to kick binary search from the solution - when you calculate $dp[i]$ you can start trying with $dp[i + 1] + 1$, descending until the success. Since there are exactly $n$ grows, there will be at most $n$ descendings and the total number of checks is linear. ?Observation? 4. We need to check whether such $j$ exists in a fast way. Recall there are few conditions for us to follow, $dp[j] \ge const$, $j \ge const$ and some string equality. If you carefully look at the restriction $j \ge const$ you can see, that when we move our dp calculation $i \rightarrow i - 1$ or make dp[i] -= 1 this lower bound on $j$ also moves only left, like in two pointers. So each moment some indexes $j$ are "available" and some are not, and the border moves only left. Finally, time for some structures. Build Suffix Array and build segment tree over it. Let's store in the leaf of the segment tree $dp[j]$ if it's already available or $- 1$ otherwise. Let's check whether $dp[i] = k$ is good. We want for string starting at $j$ be either $s_{i}, s_{i + 1}, ..., s_{i + k - 2}$, or $s_{i + 1}, s_{i + 2}, ..., s_{i + k - 1}$. Consider these cases independently (however the procedure is pretty much same). All such strings form a segment of Suffix Array, we can for example use LCP + binary search over sparse tables to find corresponding bounds. Then we just need to query this segment and check if the maximum on it is at least $k - 1$. The solution is $O(n\log n)$
|
[
"data structures",
"dp",
"string suffix structures"
] | 3,300
| null |
1064
|
A
|
Make a triangle!
|
Masha has three sticks of length $a$, $b$ and $c$ centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.
What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a triangle of positive area. Sticks should be used as triangle's sides (one stick for one side) and their endpoints should be located at triangle's vertices.
|
Suppose $c$ is the largest stick. It is known, that we can build a triangle iff $c \le a + b - 1$. So if we can build a triangle the answer is zero. Otherwise we can just increase $a$ or $b$ until the inequality above holds. So the answer is $max(0, c - (a + b - 1))$. Another approach: just bruteforce all possible triangles we can extend to (with sides $\le 100$) and select the one with smallest $a + b + c$.
|
[
"brute force",
"geometry",
"math"
] | 800
| null |
1064
|
B
|
Equations of Mathematical Magic
|
\begin{quote}
Colossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for.
\hfill Arkadi and Boris Strugatsky. Monday starts on Saturday
\end{quote}
Reading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: $a - (a \oplus x) - x = 0$ for some given $a$, where $\oplus$ stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some $x$, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many \textbf{non-negative} solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help.
|
Rewriting equation we have $a \oplus x = a - x$. If you look in the xor definition, it is easy to see, that $a \oplus x \ge a - x$, no matter $a$ and $x$ (just look at the each bit of the $a \oplus x$). And the equality handles only if bits of $x$ form a subset of bits of $a$. So the answer is $2^t$, where $t$ is the number of bits in $a$ (also known as popcount).
|
[
"math"
] | 1,200
| null |
1065
|
A
|
Vasya and Chocolate
|
There is a special offer in Vasya's favourite supermarket: if the customer buys $a$ chocolate bars, he or she may take $b$ additional bars for free. This special offer can be used any number of times.
Vasya currently has $s$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $c$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!
|
Number of chocolate bars Vasya can buy without offer is $cnt = \lfloor \frac{s}{c} \rfloor$. Number of "bundles" with $a$ bars $x = \lfloor \frac{cnt}{a} \rfloor$. Then number of additional bars $add = x \cdot b$. In result, total number of bars is $add + cnt$.
|
[
"implementation",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int s, a, b, c;
int t;
cin >> t;
for(int i = 0; i < t; ++i){
cin >> s >> a >> b >> c;
s /= c;
int x = s / a;
s %= a;
long long res = x * 1LL * (a + b);
res += s;
cout << res << endl;
}
return 0;
}
|
1065
|
B
|
Vasya and Isolated Vertices
|
Vasya has got an undirected graph consisting of $n$ vertices and $m$ edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges $(1, 2)$ and $(2, 1)$ is considered to be multiple edges. Isolated vertex of the graph is a vertex such that there is no edge connecting this vertex to any other vertex.
Vasya wants to know the minimum and maximum possible number of isolated vertices in an undirected graph consisting of $n$ vertices and $m$ edges.
|
Vasya can decrease number of isolated vertices up to $2$ using one edge and pairing them. So minimum number of isolated vertices is $max(0, n - 2m)$. To calculate maximum number of isolated vertices let's keep number of non-isolated vertices knowing that each pair connected by edge (i.e. size of clique). Let we have size of clique $cur$ and $rem$ edges remained unassigned at current step. If $rem = 0$ then answer is $n - cur$. Otherwise we need to increase clique with one vertex. Maximum number of edges we can add to connect this vertex is $add = min~(rem, cur)$. So, subtract it from $rem$ and increase $cur$ by one. Repeat this step while $rem$ greater than zero. Answer is $n - cur$. One corner case is next: if $cur = 1$, then answer is $n$, not $n - cur$.
|
[
"constructive algorithms",
"graphs"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
long long m;
cin >> n >> m;
long long cur = 1;
long long rem = m;
while(rem > 0){
long long d = min(cur, rem);
rem -= d;
++cur;
}
assert(rem == 0);
long long res = n;
if(cur > 1) res = n - cur;
cout << max(0ll, n - m * 2) << ' ' << res << endl;
return 0;
}
|
1065
|
C
|
Make It Equal
|
There is a toy building consisting of $n$ towers. Each tower consists of several cubes standing on each other. The $i$-th tower consists of $h_i$ cubes, so it has height $h_i$.
Let's define operation slice on some height $H$ as following: for each tower $i$, if its height is greater than $H$, then remove some top cubes to make tower's height equal to $H$. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to $k$ ($k \ge n$).
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
|
Let's iterate over height $pos$ of slice in decreasing order. All we need to know is a number of towers with height more than $pos$ (name it $c$) and sum of its heights $sum$. Current slice on height $pos$ is good if $k \ge sum - c \cdot pos$. Let's greedily decrease value $pos$ while slice on $pos$ is good keeping correct values $c$ and $sum$. When we found minimal good slice we can perform it increasing answer by one and "changing tower heights" just by setting new value to $sum$ equal to $c \cdot pos$. Finish algorithm when $pos$ becomes equal to minimal height of towers and make final slice.
|
[
"greedy"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 9;
int n, k, h;
int need = int(1e9);
int cnt[N];
int main() {
scanf("%d %d", &n, &k);
for(int i = 0; i < n; ++i){
int x;
scanf("%d", &x);
h = max(h, x);
need = min(need, x);
++cnt[x];
}
int pos = N - 1;
int res = 0;
long long sum = 0;
int c = 0;
while(true){
long long x = sum - c * 1LL * (pos - 1);
if(x > k){
++res;
h = pos;
sum = pos * 1LL * c;
}
--pos;
if(pos == need) break;
c += cnt[pos];
sum += cnt[pos] * 1LL * pos;
}
if(h != need) ++res;
cout << res << endl;
}
|
1065
|
D
|
Three Pieces
|
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily $8 \times 8$, but it still is $N \times N$. Each square has some number written on it, all the numbers are from $1$ to $N^2$ and all the numbers are pairwise distinct. The $j$-th square in the $i$-th row has a number $A_{ij}$ written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number $1$ (you can choose which one). Then you want to reach square $2$ (possibly passing through some other squares in process), then square $3$ and so on until you reach square $N^2$. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. \textbf{Each square can be visited arbitrary number of times}.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
|
There are a lot of different solutions for the problem. Most of them have the similar structure. The first part is to find the shortest distance between the states $(x_1, y_1, p_1)$ and $(x_2, y_2, p_2)$, where $x$ and $y$ are the coordinates of the square and $p$ is the current piece. This can be done with 0-1 bfs, Floyd or Dijkstra. Just represent the triple as a single integer by transforming it to $(x \cdot n \cdot 3 + y \cdot 3 + p)$ and do everything on that graph. The second part is to write some dp to go from $i$-th square with piece $p_1$ to $(i + 1)$-th square with piece $p_2$. The value of this $dp[n][3]$ is a pair (moves, replacements). It is easy to see that you can always choose the minimum of two such pairs while updating. Overall complexity may vary. We believe, $O(n^4)$ is achievable. However, the particular solution I coded works in $O(n^6)$.
|
[
"dfs and similar",
"dp",
"shortest paths"
] | 2,200
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define mp make_pair
#define x first
#define y second
using namespace std;
typedef pair<int, int> pt;
const int N = 12;
const int M = 305;
const int INF = 1e9;
int n;
int a[N][N];
pt pos[N * N];
pt dist[M][M];
pt operator +(const pt &a, const pt &b){
return mp(a.x + b.x, a.y + b.y);
}
int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[] = { 1, 2, 2, 1, -1, -2, -2, -1};
bool in(int x, int y){
return (0 <= x && x < n && 0 <= y && y < n);
}
int get(int x, int y, int p){
return x * n * 3 + y * 3 + p;
}
pt dp[N * N][3];
int main() {
scanf("%d", &n);
forn(i, n) forn(j, n){
scanf("%d", &a[i][j]);
--a[i][j];
pos[a[i][j]] = mp(i, j);
}
forn(i, M) forn(j, M) dist[i][j] = mp(INF, INF);
forn(i, M) dist[i][i] = mp(0, 0);
forn(x, n) forn(y, n){
forn(i, 8){
int nx = x + dx[i];
int ny = y + dy[i];
if (in(nx, ny))
dist[get(x, y, 0)][get(nx, ny, 0)] = mp(1, 0);
}
for (int i = -n + 1; i <= n - 1; ++i){
int nx = x + i;
int ny = y + i;
if (in(nx, ny))
dist[get(x, y, 1)][get(nx, ny, 1)] = mp(1, 0);
ny = y - i;
if (in(nx, ny))
dist[get(x, y, 1)][get(nx, ny, 1)] = mp(1, 0);
}
forn(i, n){
int nx = x;
int ny = i;
dist[get(x, y, 2)][get(nx, ny, 2)] = mp(1, 0);
nx = i;
ny = y;
dist[get(x, y, 2)][get(nx, ny, 2)] = mp(1, 0);
}
forn(i, 3) forn(j, 3){
if (i != j){
dist[get(x, y, i)][get(x, y, j)] = mp(1, 1);
}
}
}
forn(k, M) forn(i, M) forn(j, M)
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
forn(i, N * N) forn(j, 3) dp[i][j] = mp(INF, INF);
dp[0][0] = dp[0][1] = dp[0][2] = mp(0, 0);
forn(i, n * n - 1) forn(j, 3) forn(k, 3)
dp[i + 1][k] = min(dp[i + 1][k], dp[i][j] + dist[get(pos[i].x, pos[i].y, j)][get(pos[i + 1].x, pos[i + 1].y, k)]);
pt ans = mp(INF, INF);
ans = min(ans, dp[n * n - 1][0]);
ans = min(ans, dp[n * n - 1][1]);
ans = min(ans, dp[n * n - 1][2]);
printf("%d %d\n", ans.x, ans.y);
return 0;
}
|
1065
|
E
|
Side Transmutations
|
Consider some set of distinct characters $A$ and some string $S$, consisting of exactly $n$ characters, where each character is present in $A$.
You are given an array of $m$ integers $b$ ($b_1 < b_2 < \dots < b_m$).
You are allowed to perform the following move on the string $S$:
- Choose some valid $i$ and set $k = b_i$;
- Take the first $k$ characters of $S = Pr_k$;
- Take the last $k$ characters of $S = Su_k$;
- Substitute the first $k$ characters of $S$ with the reversed $Su_k$;
- Substitute the last $k$ characters of $S$ with the reversed $Pr_k$.
For example, let's take a look at $S =$ "abcdefghi" and $k = 2$. $Pr_2 =$ "ab", $Su_2 =$ "hi". Reversed $Pr_2 =$ "ba", $Su_2 =$ "ih". Thus, the resulting $S$ is "{\textbf{ih}cdefg\textbf{ba}}".
The move can be performed arbitrary number of times (possibly zero). Any $i$ can be selected multiple times over these moves.
Let's call some strings $S$ and $T$ equal if and only if there exists such a sequence of moves to transmute string $S$ to string $T$. For the above example strings "abcdefghi" and "ihcdefgba" are equal. Also note that this implies $S = S$.
The task is simple. Count the number of distinct strings.
The answer can be huge enough, so calculate it modulo $998244353$.
|
Let's take a look at any operation. You can notice that each letter can only go from position $i$ to $n - i - 1$ ($0$-indexed). Then, doing some operation twice is the same as doing that operation zero times. Now consider some set of operations $l_1, l_2, \dots, l_k$, sorted in increasing order. Actually, they do the following altogether. Replace segment $[l_{k - 1}..l_k)$ with the reversed segment $((n - l_k - 1)..(n - l_{k - 1} - 1)]$ and vice versa. Then replace segment $[l_{k - 3}..l_{k - 2})$ with the reversed segment $((n - l_{k - 2} - 1)..(n - l_{k - 3} - 1)]$ and vice versa. And continue until you reach the first pair. Segment $[0..l_1)$ might also be included in the answer when the parity is right. Moreover, every subset of segments $[0..l_1), [l_1, l_2), \dots [l_{k - 1}, l_k)$ is achievable. So for each segment you can either swap it or not. Let's translate it to math language. Let $cnt_i$ be the number of such pairs of strings $x$ and $y$ that $x \le y$. Why is there such an order? You want to consider only unique strings, thus, you need to pick exactly one of equal strings from each component. Let it be the smallest one. Then for each segment of the set you have $cnt_{len}$ pairs to choose from, where $len$ is the length of that segment. And that part of the formula is: $cnt_{b_1} \cdot \prod \limits_{i = 1}^{m} cnt_{b_i - b_{i - 1}}$. However, the part covered by zero segments is left. There are $AL^{n - 2b_m}$ possible strings up there. $cnt_i$ is actually a number of all pairs of strings of length $i$ plus the number of all pairs of equal strings of length $i$ divided by $2$. $cnt_i = \frac{AL^{2i} + AL^i}{2}$. Overall complexity: $O(m \log n)$.
|
[
"combinatorics",
"strings"
] | 2,300
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 200 * 1000 + 13;
const int MOD = 998244353;
int n, m, A;
int b[N];
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
return a;
}
int mul(int a, int b){
return (a * 1ll * b) % MOD;
}
int binpow(int a, int b){
int res = 1;
while (b){
if (b & 1)
res = mul(res, a);
a = mul(a, a);
b >>= 1;
}
return res;
}
int cnt(int x){
int base = binpow(A, x);
return mul(add(mul(base, base), base), (MOD + 1) / 2);
}
int main() {
scanf("%d%d%d", &n, &m, &A);
forn(i, m)
scanf("%d", &b[i]);
int ans = binpow(A, n - b[m - 1] * 2);
ans = mul(ans, cnt(b[0]));
forn(i, m - 1)
ans = mul(ans, cnt(b[i + 1] - b[i]));
printf("%d\n", ans);
return 0;
}
|
1065
|
F
|
Up and Down the Tree
|
You are given a tree with $n$ vertices; its root is vertex $1$. Also there is a token, initially placed in the root. You can move the token to other vertices. Let's assume current vertex of token is $v$, then you make any of the following two possible moves:
- move down to any \textbf{leaf} in subtree of $v$;
- if vertex $v$ is a leaf, then move up to the parent no more than $k$ times. In other words, if $h(v)$ is the depth of vertex $v$ (the depth of the root is $0$), then you can move to vertex $to$ such that $to$ is an ancestor of $v$ and $h(v) - k \le h(to)$.
Consider that root is not a leaf (even if its degree is $1$). Calculate the maximum number of different leaves you can visit during one sequence of moves.
|
Let's calculate answer in two steps. At first, let's calculate for each vertex $v$ $drev(v)$ - what we can gain if we must return from subtree of $v$ in the end. We need only pair of values: minimal possible depth we can acquire to move up from subtree of $v$ and maximal number of different leaves we can visit. Note, that this two values are independent since we must return from $v$ and if for some child $to$ of $v$ we can return from it, it's profitable to visit $to$ and return. But if we can't return from $to$ so we are prohibited to descent to $to$. So, $drev(v).second$ (number of visited leaves) is just a sum of all $drev(to).second$ if $drev(to).first \le h_v$. Also note that we can always reorder all children in such way that last visited vertex $to$ will have minimal $drev(to).first$. So $drev(to).first$ (minimal possible depth) is a minimum over all $drev(to).first$. At second, let's calculate $d(v)$ - maximal number of different leaves we can visit if we don't need to return from subtree of $v$. It can be calculated quite easy using array $drev(v)$. We just need to choose child $to$ we will not return from, so from vertex $to$ we will take value $d(to)$ and from other childen (which we can return from) value $drev(v).second$. Result complexity is $O(n)$.
|
[
"dfs and similar",
"dp",
"trees"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {
return out << "(" << p.x << ", " << p.y << ")";
}
template<class A> ostream& operator <<(ostream& out, const vector<A> &v) {
out << "[";
fore(i, 0, v.size()) {
if(i) out << ", ";
out << v[i];
}
return out << "]";
}
const int INF = int(1e9);
const li INF64 = li(1e18);
const int N = 1000 * 1000 + 555;
int n, k;
vector<int> g[N];
inline bool read() {
if(!(cin >> n >> k))
return false;
fore(i, 1, n) {
int p; assert(scanf("%d", &p) == 1);
p--;
g[p].push_back(i);
g[i].push_back(p);
}
return true;
}
int h[N];
pt drev[N];
void calcRev(int v, int p) {
drev[v] = pt(INF, 0);
for(int to : g[v]) {
if(to == p) continue;
h[to] = h[v] + 1;
calcRev(to, v);
if(drev[to].x <= h[v]) {
drev[v].x = min(drev[v].x, drev[to].x);
drev[v].y += drev[to].y;
}
}
if(p >= 0 && g[v].size() == 1)
drev[v] = pt(h[v] - k, 1);
}
int d[N];
void calcAns(int v, int p) {
d[v] = (p >= 0 && g[v].size() == 1);
for(int to : g[v]) {
if(to == p) continue;
calcAns(to, v);
int tmp = drev[v].y;
if(drev[to].x <= h[v])
tmp -= drev[to].y;
d[v] = max(d[v], tmp + d[to]);
}
}
inline void solve() {
h[0] = 0;
calcRev(0, -1);
calcAns(0, -1);
cout << d[0] << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1065
|
G
|
Fibonacci Suffix
|
Let's denote (yet again) the sequence of Fibonacci strings:
$F(0) = $ 0, $F(1) = $ 1, $F(i) = F(i - 2) + F(i - 1)$, where the plus sign denotes the concatenation of two strings.
Let's denote the \textbf{lexicographically sorted} sequence of suffixes of string $F(i)$ as $A(F(i))$. For example, $F(4)$ is 01101, and $A(F(4))$ is the following sequence: 01, 01101, 1, 101, 1101. Elements in this sequence are numbered from $1$.
Your task is to print $m$ first characters of $k$-th element of $A(F(n))$. If there are less than $m$ characters in this suffix, then output the whole suffix.
|
Suppose we added all the suffixes of $F(n)$ into a trie. Then we can find $k$-th suffix by descending the trie, checking the sizes of subtrees to choose where to go on each iteration. The model solution actually does that, but computes the sizes of subtrees without building the whole trie. Recall that if we insert all suffixes of a string into the trie, then the size of subtree of some vertex is equal to the number of occurences of the string denoted by this vertex in the original string. Since in our problem the strings are recurrent, we may use prefix automaton to count the number of occurences. To calculate the number of occurences of string $s$ in $F(x)$, let's build prefix function for $s$, and an automaton $A_{p, c}$ which tells the value of prefix function, if the previous value was $p$, and we appended $c$ to the string (the same approach is used in KMP substring search algorithm). Then, let's build another automaton that will help us work with Fibonacci string: $F_{p, x}$ - what will be the value of prefix function, if we append $F(x)$ to the string? For $x = 0$ and $x = 1$, this automaton can be easily built using $A_{p, 0}$ and $A_{p, 1}$; and for $x > 1$, we may build $F_{p, x}$ using the automatons for $x - 2$ and $x - 1$. We also have to keep track of the number of occurences, that can be done with another automaton on fibonacci strings. There is a corner case when we need to stop descending the trie; to handle it, we need to check whether some string is a suffix of $F(n)$, but that can be easily made by checking if $F_{0, n} = |s|$. Each step in trie forces us to do up to three (depending on your implementation) queries like "count the number of occurences of some string in $F(n)$", so overall the solution works in $O(n m^2)$.
|
[
"strings"
] | 2,700
|
#include <bits/stdc++.h>
using namespace std;
typedef long long li;
const li INF64 = li(1e18);
li add(li x, li y)
{
return min(x + y, INF64);
}
const int N = 243;
int A1[N][2];
li A2[N][N];
int A3[N][N];
int n, m;
li k;
int z;
int p[N];
void build(const string& s)
{
z = (int)(s.size());
p[0] = 0;
for(int i = 1; i < z; i++)
{
int j = p[i - 1];
while(j > 0 && s[j] != s[i])
j = p[j - 1];
if(s[j] == s[i])
j++;
p[i] = j;
}
for(int i = 0; i <= z; i++)
for(int j = 0; j < 2; j++)
{
if(i < z && s[i] == char('0' + j))
A1[i][j] = i + 1;
else if(i == 0)
A1[i][j] = 0;
else
A1[i][j] = A1[p[i - 1]][j];
}
for(int i = 0; i <= z; i++)
for(int j = 0; j < 2; j++)
{
A3[i][j] = A1[i][j];
A2[i][j] = (A3[i][j] == z ? 1 : 0);
}
for(int i = 2; i <= n; i++)
for(int j = 0; j <= z; j++)
{
A3[j][i] = A3[A3[j][i - 2]][i - 1];
A2[j][i] = add(A2[j][i - 2], A2[A3[j][i - 2]][i - 1]);
}
}
int main()
{
cin >> n >> k >> m;
string cur = "";
for(int i = 0; i < m; i++)
{
if(cur != "") build(cur);
li x = 0;
if(cur != "" && A3[0][n] == i)
x = 1;
if(k == 1 && x == 1)
break;
k -= x;
build(cur + '0');
li x1 = A2[0][n];
if(k > x1)
{
cur += '1';
k -= x1;
}
else
cur += '0';
}
cout << cur << endl;
return 0;
}
|
1066
|
A
|
Vova and Train
|
Vova plans to go to the conference by train. Initially, the train is at the point $1$ and the destination point of the path is the point $L$. The speed of the train is $1$ length unit per minute (i.e. at the first minute the train is at the point $1$, at the second minute — at the point $2$ and so on).
There are lanterns on the path. They are placed at the points with coordinates divisible by $v$ (i.e. the first lantern is at the point $v$, the second is at the point $2v$ and so on).
There is also \textbf{exactly} one standing train which occupies all the points from $l$ to $r$ inclusive.
Vova can see the lantern at the point $p$ if $p$ is divisible by $v$ and there is no standing train at this position ($p \not\in [l; r]$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.
Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $t$ different conferences, so you should answer $t$ \textbf{independent} queries.
|
What is the number of lanterns Vova will see from $1$ to $L$? This number is $\lfloor\frac{L}{v}\rfloor$. Now we have to subtract the number of lanters in range $[l; r]$ from this number. This number equals to $\lfloor\frac{r}{v}\rfloor - \lfloor\frac{l - 1}{v}\rfloor$. So the answer is $\lfloor\frac{L}{v}\rfloor$ - $\lfloor\frac{r}{v}\rfloor$ + $\lfloor\frac{l - 1}{v}\rfloor$.
|
[
"math"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
int L, v, l, r;
cin >> L >> v >> l >> r;
cout << L / v - r / v + (l - 1) / v << endl;
}
return 0;
}
|
1066
|
B
|
Heaters
|
Vova's house is an array consisting of $n$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $i$-th element of the array is $1$ if there is a heater in the position $i$, otherwise the $i$-th element of the array is $0$.
Each heater has a value $r$ ($r$ is the same for all heaters). This value means that the heater at the position $pos$ can warm up all the elements in range $[pos - r + 1; pos + r - 1]$.
Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater.
Vova's target is to warm up the whole house (all the elements of the array), i.e. if $n = 6$, $r = 2$ and heaters are at positions $2$ and $5$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $3$ elements will be warmed up by the first heater and the last $3$ elements will be warmed up by the second heater).
Initially, all the heaters are off.
But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the \textbf{minimum} number of heaters on in such a way that each element of his house is warmed up by at least one heater.
Your task is to find this number of heaters or say that it is impossible to warm up the whole house.
|
Let's solve this problem greedily. Let $last$ be the last position from the left covered by at least one heater. Initially, $last$ equals -1. While $last < n - 1$, lets repeat the following process: firstly, we have to find the rightmost heater in range $(max(-1, last - r + 1); last + r]$. It can be done in time $O(n)$ because of given constrains or in $O(1)$ using precalculated prefix values for each $i$ in range $[0; n - 1]$. If there is no such heater then the answer is -1, otherwise let's set $last := pos + r - 1$, increase the answer by $1$ and repeat the process if $last < n - 1$. There is another one solution to this problem. Assume that the initial answer equals to the total number of heaters. Let's calculate an array $cnt$ of length $n$, where $cnt_i$ means the number of heaters covering the $i$-th element. It can be done in $O(n^2)$. This array will mean that we are switch all the heaters on and we know for each element the number of heaters covers this element. Now if for at least $i \in [0, n - 1]$ holds $cnt_i = 0$ then the answer is -1. Otherwise let's switch useless heaters off. Let's iterate over all heaters from left to right. Let the current heater have position $i$. We need to check if it is useless or not. Let's iterate in range $[max(0, i - r + 1), min(n - 1, i + r - 1)]$ and check if there is at least one element $j$ in this segment such that $cnt_j = 1$. If there is then the current heater is not useless and we cannot switch it off. Otherwise we can decrease the answer by $1$, switch this heater off (decrease $cnt_j$ for all $j$ in range $[max(0, i - r + 1), min(n - 1, i + r - 1)]$) and continue the process.
|
[
"greedy",
"two pointers"
] | 1,500
|
#include <vector>
#include <iostream>
#define forn(i,n) for (int i=0; i<int(n); i++)
using namespace std;
const int N = 2e5;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, r; cin >> n >> r;
vector<int> a(n);
vector<int> cnt(n);
int ans = 0;
forn(i, n)
{
cin >> a[i];
if (a[i])ans++;
if (a[i])
for (int j = max(0, i - r + 1); j < min(n, i + r); ++j)
cnt[j]++;
}
forn(i, n)
if (!cnt[i])
{
cout << -1;
return 0;
}
forn(i, n)
{
bool fl = true;
if (a[i])
for (int j = max(0, i - r + 1); j < min(n, i + r); ++j)
if (cnt[j] == 1)
{
fl = false;
break;
}
if (fl && a[i])
{
ans--;
for (int j = max(0, i - r + 1); j < min(n, i + r); ++j)
cnt[j]--;
}
}
cout << ans;
}
|
1066
|
C
|
Books Queries
|
You have got a shelf and want to put some books on it.
You are given $q$ queries of three types:
- L $id$ — put a book having index $id$ on the shelf to the left from the leftmost existing book;
- R $id$ — put a book having index $id$ on the shelf to the right from the rightmost existing book;
- ? $id$ — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $id$ will be leftmost or rightmost.
You can assume that the first book you will put can have any position (it does not matter) and queries of type $3$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $id$s don't repeat in queries of first two types.
Your problem is to answer all the queries of type $3$ in order they appear in the input.
Note that after answering the query of type $3$ all the books remain on the shelf and the relative order of books does not change.
\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}
|
Let imagine our shelf as an infinite array. Let's carry the rightmost free position from the left of our shelf (let it be $l$ and initially it equals to $0$) and the leftmost free position from the right of our shelf (let it be $r$ and initially it equals to $0$). Also let's carry the array $pos$ of length $2 \cdot 10^5$ where $pos_i$ will be equal to the position in our imaginary array of the book with a number $i$. Let's put the first book to the position $0$. Also let's save that $pos_{id}$ (where $id$ is the number of the first book) equals to $0$. How will change $l$ and $r$? $l$ will become $-1$ and $r$ will become $1$. Now let's process queries one by one. If now we have the query of type $1$ with a book with a number $id$, then let's set $pos_{id} := l$ and set $l := l - 1$. The query of type $2$ can be processed similarly. Now what about queries of type $3$? The answer to this query equals to $min(|pos_{id} - l|, |pos_{id} - r|) - 1$, where $|v|$ is the absolute value of $v$.
|
[
"implementation"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
const int M = 200 * 1000 + 11;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
vector<int> pos(M);
int curl = 0;
int curr = 0;
for (int i = 0; i < q; ++i) {
string type;
int id;
cin >> type >> id;
if (i == 0) {
pos[id] = curl;
--curl;
++curr;
} else {
if (type == "L") {
pos[id] = curl;
--curl;
} else if (type == "R") {
pos[id] = curr;
++curr;
} else {
cout << min(abs(pos[id] - curl), abs(pos[id] - curr)) - 1 << "\n";
}
}
}
return 0;
}
|
1066
|
D
|
Boxes Packing
|
Maksim has $n$ objects and $m$ boxes, each box has size exactly $k$. Objects are numbered from $1$ to $n$ in order from left to right, the size of the $i$-th object is $a_i$.
Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the $i$-th object fits in the current box (the remaining size of the box is greater than or equal to $a_i$), he puts it in the box, and the remaining size of the box decreases by $a_i$. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.
Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, \textbf{he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has}. Your task is to say the maximum number of objects Maksim can pack in boxes he has.
Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).
|
The first solution is some kind of a straight-forward understanding the problem. Let's do binary search on the answer. So our problem is to find the smallest $x$ such that the suffix of the array $a$ starting from the position $x$ can be packed in boxes. It is easy to see that if we can do it for some $x$ then we always can do it for $x+1$. And to find the answer for the fixed $x$ we have to simulate the process described in the problem statement starting from the position $x$. Okay, this is $O(n \log n)$ solution. The second solution is more interesting than the first one. The approach is to reverse the initial array, simulate the process from the first position of reversed array and then all the objects we can pack are in the best answer and there is no better answer at all. Why it works? Let's take a look on the last box in the best answer if we will go from left to right in the initial array. Let objects in this box be $a_{lst_1}, a_{lst_2}, \dots, a_{lst_x}$. What do we see? $\sum\limits_{i = 1}^{x}a_{lst_i} \le k$. So all these objects are fit in the last box (obviously). Now if we will iterate over objects from right to left, these objects will fit also! It means that we cannot do worse by such a transform (reversing) at least for the last box. But what will happen if we can put some of the previous objects in this box? Well, it will not make worse for this box, but what about next boxes (previous boxes in straight notation)? Let objects in the penultimate box be $a_{prev_1}, a_{prev_2}, \dots, a_{prev_y}}$. What do we see? These objects are fit in this box (obviously again). What will happen if we will put in the last box one or more objects of this box? Then the left border of objects which we will put in it will not increase because we decrease the number of object in this box. So we can see that for previous boxes this condition is also satisfied. So we can solve the problem with this approach. Time complexity of this solution is $O(n)$.
|
[
"binary search",
"implementation"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m, k;
cin >> n >> m >> k;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
reverse(a.begin(), a.end());
int rem = 0;
for (int i = 0; i < n; ++i) {
if (rem - a[i] < 0) {
if (m == 0) {
cout << i << endl;
return 0;
} else {
--m;
rem = k - a[i];
}
} else {
rem -= a[i];
}
}
cout << n << endl;
return 0;
}
|
1066
|
E
|
Binary Numbers AND Sum
|
You are given two huge binary integer numbers $a$ and $b$ of lengths $n$ and $m$ respectively. You will repeat the following process: if $b > 0$, then add to the answer the value $a~ \&~ b$ and divide $b$ by $2$ rounding down (i.e. remove the last digit of $b$), and repeat the process again, otherwise stop the process.
The value $a~ \&~ b$ means bitwise AND of $a$ and $b$. Your task is to calculate the answer modulo $998244353$.
Note that you should add the value $a~ \&~ b$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $a = 1010_2~ (10_{10})$ and $b = 1000_2~ (8_{10})$, then the value $a~ \&~ b$ will be equal to $8$, not to $1000$.
|
To solve this problem let's take a look which powers of $2$ in $a$ will be affected by powers of $2$ in $b$. Firstly, let's reverse numbers. Let's carry the current power of $2$ (let it be $pw$), the current sum of powers of $2$ in $a$ from the position $0$ to the current position inclusive (let it be $res$) and the answer is $ans$. Initially, $pw = 1$, $res = 0$ and $ans = 0$. Let's iterate over all bits of $b$ from $0$ to $m - 1$. Let the current bit in $b$ have the number $i$. Firstly, if $i < n$ and $a_i = 1$ then set $res := res + pw$ (in other words, we add to the sum of powers of $2$ in $a$ the current power of $2$). If $b_i = 1$ then this bit will add to the answer all the powers of $2$ in $a$ from $0$ to $i$ inclusive (in other words, $res$), so if it is, then set $ans := ans + res$. And after all we can set $pw := pw + pw$ and go on to $i+1$. And don't forget to take all values modulo $998244353$ to avoid overflow.
|
[
"data structures",
"implementation",
"math"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int a, int b) {
a += b;
if (a < 0) a += MOD;
if (a >= MOD) a -= MOD;
return a;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m;
cin >> n >> m;
string s, t;
cin >> s >> t;
int pw = 1;
int res = 0;
int ans = 0;
for (int i = 0; i < m; ++i) {
if (i < n && s[n - i - 1] == '1') {
res = add(res, pw);
}
if (t[m - i - 1] == '1') {
ans = add(ans, res);
}
pw = add(pw, pw);
}
cout << ans << endl;
return 0;
}
|
1066
|
F
|
Yet another 2D Walking
|
Maksim walks on a Cartesian plane. Initially, he stands at the point $(0, 0)$ and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point $(0, 0)$, he can go to any of the following points in one move:
- $(1, 0)$;
- $(0, 1)$;
- $(-1, 0)$;
- $(0, -1)$.
There are also $n$ \textbf{distinct} key points at this plane. The $i$-th point is $p_i = (x_i, y_i)$. It is guaranteed that $0 \le x_i$ and $0 \le y_i$ and there is no key point $(0, 0)$.
Let the first level points be such points that $max(x_i, y_i) = 1$, the second level points be such points that $max(x_i, y_i) = 2$ and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level $i + 1$ if he does not visit all the points of level $i$. He starts visiting the points from the minimum level of point from the given set.
The distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$ where $|v|$ is the absolute value of $v$.
Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.
\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}
|
The main idea is that we don't need more than $2$ border points on each level. So if we consider than the point $p = (x_p, y_p)$ is less than point $q = (x_q, y_q)$ when $p_x < q_x$ or $p_x = q_x$ and $p_y > q_y$ then let's distribute all the points by their levels using std::map or something like it, sort points on each level by the comparator above and remain the first one and the last one on each level. Also let's add the fictive level $0$ with the point $(0, 0)$. It is always true to remain at most $2$ points and can be easily proved but this fact is very intuitive I think. Now let's do dynamic programming on the points. $dp_{i, j}$ means that now we are at the level $i$ and stay in the first point (if $j = 0$) or in the last point (if $j = 1$) and we are already visit all the points on the level $i$. The value of this dynamic programming is the minimum possible total distance to reach this state. Initially, $dp_{0, 0} = dp_{0, 1} = 0$, other values are equal to $\infty$. Let's calculate this dynamic programming in order of increasing levels. Let $p_{lvl, 0}$ be the first key point at the level $lvl$ and $p_{lvl, 1}$ be the last key point at the level $lvl$. Now if we are at the level $lvl$ and the previous level is $plvl$, these $4$ transitions are sufficient to calculate states of dynamic programming on the current level: $dp_{lvl, 0} = min(dp_{lvl, 0}, dp_{plvl, 0} + dist(p_{plvl, 0}, p_{lvl, 1}) + dist(p_{lvl, 1}, p_{lvl, 0})$; $dp_{lvl, 0} = min(dp_{lvl, 0}, dp_{plvl, 1} + dist(p_{plvl, 1}, p_{lvl, 1}) + dist(p_{lvl, 1}, p_{lvl, 0})$; $dp_{lvl, 1} = min(dp_{lvl, 1}, dp_{plvl, 0} + dist(p_{plvl, 0}, p_{lvl, 0}) + dist(p_{lvl, 0}, p_{lvl, 1})$; $dp_{lvl, 1} = min(dp_{lvl, 1}, dp_{plvl, 1} + dist(p_{plvl, 1}, p_{lvl, 0}) + dist(p_{lvl, 0}, p_{lvl, 1})$. There $dist(p, q)$ means the distance between points $p$ and $q$. Let last level we have be $lst$. After calculating this dynamic programming the answer is $min(dp_{lst, 0}, dp_{lst, 1})$.
|
[
"dp"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
const long long INF64 = 1e18;
long long dist(pair<int, int> a, pair<int, int> b) {
return abs(a.first - b.first) + abs(a.second - b.second);
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
map<int, vector<pair<int, int>>> pts;
cin >> n;
for (int i = 0; i < n; ++i) {
int x, y;
cin >> x >> y;
pts[max(x, y)].push_back(make_pair(x, y));
}
pts[0].push_back(make_pair(0, 0));
for (auto &it : pts) {
sort(it.second.begin(), it.second.end(), [&](pair<int, int> a, pair<int, int> &b) {
if (a.first == b.first)
return a.second > b.second;
return a.first < b.first;
});
}
vector<vector<long long>> dp(int(pts.size()) + 1, vector<long long>(2, INF64));
dp[0][0] = dp[0][1] = 0;
int lvl = 0;
int prv = 0;
for (auto &it : pts) {
++lvl;
pair<int, int> curl = it.second[0];
pair<int, int> curr = it.second.back();
pair<int, int> prvl = pts[prv][0];
pair<int, int> prvr = pts[prv].back();
dp[lvl][0] = min(dp[lvl][0], dp[lvl - 1][0] + dist(prvl, curr) + dist(curl, curr));
dp[lvl][0] = min(dp[lvl][0], dp[lvl - 1][1] + dist(prvr, curr) + dist(curl, curr));
dp[lvl][1] = min(dp[lvl][1], dp[lvl - 1][0] + dist(prvl, curl) + dist(curl, curr));
dp[lvl][1] = min(dp[lvl][1], dp[lvl - 1][1] + dist(prvr, curl) + dist(curl, curr));
prv = it.first;
}
cout << min(dp[lvl][0], dp[lvl][1]) << endl;
return 0;
}
|
1067
|
A
|
Array Without Local Maximums
|
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of $n$ numbers from $1$ to $200$. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally:
$a_{1} \le a_{2}$,
$a_{n} \le a_{n-1}$ and
$a_{i} \le max(a_{i-1}, \,\, a_{i+1})$ for all $i$ from $2$ to $n-1$.
Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from $1$ to $200$. Since the number of ways can be big, print it modulo $998244353$.
|
Let's find solution with complexity $O(n \cdot a^2)$. We can count $dp[prefix][a][flag]$ - quantity of ways to restore element from $1$ to $pref$ with last element equalls to $a$, $flag = 0$ means that previous element is less then the last or last element is first, $flag = 1$ - the opposite. So $dp[pref][a][0] = \sum_{i=1}^{a-1} (dp[pref-1][i][1] + dp[pref-1][i][0])$, $dp[pref][a][1] = dp[pref-1][a][0] + \sum_{i=a}^{200} dp[pref-1][i][1]$. Now let's count $prefix \_ sums[a][flag] = \sum_{i=1}^{a} dp[pref][i][flag]$ on each prefix before counting all $dp[pref]$, so we can recalculate dp in O(1) time. Complexity is $O(n \cdot a)$.
|
[
"dp"
] | 1,900
| null |
1067
|
B
|
Multihedgehog
|
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least $3$ (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself $k$-multihedgehog.
Let us define $k$-multihedgehog as follows:
- $1$-multihedgehog is hedgehog: it has one vertex of degree at least $3$ and some vertices of degree 1.
- For all $k \ge 2$, $k$-multihedgehog is $(k-1)$-multihedgehog in which the following changes has been made for each vertex $v$ with degree 1: let $u$ be its only neighbor; remove vertex $v$, create a new hedgehog with center at vertex $w$ and connect vertices $u$ and $w$ with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby $k$-multihedgehog is a tree. Ivan made $k$-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed $k$-multihedgehog.
|
Solution 1: Firstly let's find all vertices with degree $1$. Now we can delete them and all, verticies which were incident to them must became verticies with degree $1$. And also for each new veretice with degree $1$ we must have already deleted not less then $3$ verticies. If initial graph was $k$-multihedgehog, after deleting vertices with degree $1$ it would became $k-1$-multihedgehog. It could be realised using bfs starting from all initial vertices with degree $1$. Complexity is $O(n)$. Solution 2: First of all let's find diametr of the graph. After that we can find middle vertex in diameter and check if it is a center of $k$-multihedgehog using simple dfs. Complexity is $O(n)$.
|
[
"dfs and similar",
"graphs",
"shortest paths"
] | 1,800
| null |
1067
|
C
|
Knights
|
Ivan places knights on infinite chessboard. Initially there are $n$ knights. If there is free cell which is under attack of at least $4$ knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the end does not depend on the order in which new knights are placed.
Ivan asked you to find initial placement of exactly $n$ knights such that in the end there will be at least $\lfloor \frac{n^{2}}{10} \rfloor$ knights.
|
If after some loops of the process we will have two neighboring lines with length $x$ total complexity of knights would be not less than $O( \frac{x^2}{4} )$. In this construction: $0$ - initial placement. $1, \,\, 2$ - added knights. Would be two neighboring lines with length $O(\frac{2 \cdot n}{3})$ so total complexity of knights would be $O( \frac{(\frac{2 \cdot n}{3})^2}{4} ) = O( \frac{n^2}{9} )$. The possible way to facilitate the invention this (or over) solutions is to write process modeling. Bonus: Solve this problem with complexity $O( \frac{n^2}{6} )$.
|
[
"constructive algorithms"
] | 2,600
| null |
1067
|
D
|
Computer Game
|
Ivan plays some computer game. There are $n$ quests in the game. Each quest can be upgraded once, this increases the reward for its completion. Each quest has $3$ parameters $a_{i}$, $b_{i}$, $p_{i}$: reward for completing quest before upgrade, reward for completing quest after upgrade ($a_{i} < b_{i}$) and probability of successful completing the quest.
Each second Ivan can try to complete one quest and he will succeed with probability $p_{i}$. In case of success Ivan will get the reward and opportunity to upgrade any one quest (not necessary the one he just completed). In case of failure he gets nothing. Quests \textbf{do not vanish} after completing.
Ivan has $t$ seconds. He wants to maximize expected value of his total gain after $t$ seconds. Help him to calculate this value.
|
Let's denote $max(b_{i} p_{i})$ as $M$. Independent of our strategy we cannot get more than $M$ in one second (in expected value). But if we could upgrade one quest, we would upgrade the quest which maximizes $b_{i} p_{i}$ and then try to complete only this quest each second, thus getting $+M$ to expected value each second. Therefore, our strategy looks like this: try to complete quests in some order, once we complete one quest we will always get $+M$ to expected value each second. This observation leads to DP solution. Once we have one quest completed we already know what we will get, so interesting states are only those in which no quests are completed yet. Then it is not important what quests we tried to complete before, the only important parameter is remaining time. $dp_{t+1} = max(p_{i} (a_{i} + tM) + (1 - p_{i}) dp_{t})$. If we succeed then we will get $a_{i}$ as a reward and for remaining $t$ seconds we will get $M$ each second, otherwise we get nothing and now only $t$ seconds left. This solution works in $O(nT)$ time which is too slow. We can slightly rewrite the formula for transition: $dp_{t+1} = max(p_{i} (a_{i} + tM) + (1 - p_{i}) dp_{t}) = dp_{t} + max(p_{i} (tM - dp_{t}) + p_{i} a_{i})$. Now we can see that we take maximum value of functions $p_{i} \cdot x + p_{i} a_{i}$ in point $x_{t} = tM - dp_{t}$. We can build convex hull on these lines thus getting $O(n \log n + T \log n)$ solution. But that's not all. We can actually prove that $x_{t} \le x_{t+1}$ or, after some substitutions and simplifications, $dp_{t+1} - dp_{t} \le M$. This we will prove by actual meaning of $dp_{t}$. Take optimal solution for $t+1$ seconds and do the same for $t$ seconds, except that we don't have last second, so we will just drop our action. But we can't gain more than $M$ in one second, so this drop cannot decrease answer more than $M$. Thus the inequality is proven. This means that we only move right along over convex hull, so for each line there will be consecutive seconds in which we are using that line. If we could somehow determine these segments of times for each line and learn how to make many DP transitions at once then we would solve the problem even faster. Let's start with learning how to make many DP transitions (when we are staying on one line for the whole time). It is more clear using first formula for DP transition: $dp_{t+1} = p_{i} (a_{i} + tM) + (1 - p_{i}) dp_{t}$ (we don't have max now because we already know which line to use). We can see that to get vector $\begin{pmatrix} dp_{t+1} & t+1 & 1 \end{pmatrix}^{T}$ from vector $\begin{pmatrix} dp_{t} & t & 1 \end{pmatrix}^{T}$ we can apply linear transformation i.e. multiply by some matrix: $\begin{pmatrix} dp_{t+1} \\ t+1 \\ 1 \end{pmatrix} = \begin{pmatrix} 1 - p_{i} & p_{i} M & p_{i} a_{i} \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{pmatrix} \begin{pmatrix} dp_{t} \\ t \\ 1 \end{pmatrix}$ To apply it $k$ times just use binary exponentiation to get $k$-th power of transition matrix. To determine how long we actually have to stay on given line we will use binary search on answer. We know for which value of $x$ we should move to the next line and we know that $x$ increases with each second, so we can try to stay on given line for some time and see if we should actually change the line. This is already $O(n (\log n + \log ^{2} T) )$ solution, but we can improve it one more time by making binary exponentiation and binary search on power for this exponentiation at the same time. Final complexity is $O(n (\log n + \log T) )$
|
[
"dp",
"greedy",
"math",
"probabilities"
] | 3,100
| null |
1067
|
E
|
Random Forest Rank
|
Let's define rank of undirected graph as rank of its adjacency matrix in $\mathbb{R}^{n \times n}$.
Given a tree. Each edge of this tree will be deleted with probability $1/2$, all these deletions are independent. Let $E$ be the expected rank of resulting forest. Find $E \cdot 2^{n-1}$ modulo $998244353$ (it is easy to show that $E \cdot 2^{n-1}$ is an integer).
|
I'll try to explain how to come up with this solution rather than just state the fact. For those who are more interested in getting AC, here is your fact: rank of a forest is twice the size of maximal matching. When we see expected value, we usually want to somehow rewrite the thing under the expected value, apply linearity of expectation and then calculate some independent values. But that's not the case: rank behave strangely and we cannot rewrite it as sum of something, at least I don't know any such solutions (if you do, please write them in the comments). So it looks like we are forced to understand what rank is. The rank of a matrix is a size of its largest non-vanishing minor. But our matrix is symmetric, maybe we can look only at symmetric minors (in a sense that we use the same set of rows and columns)? This is actually true but it is just a fact from linear algebra (seems to be not very well known) and has little to do with our problem, so I'll drop its proof and if someone is interested, ask me in comments. Why do we like symmetric minors? Because they correspond to induced subgraphs of our graph. And all induced subgraphs of a forest are forests too! So let's study when a forest has full rank. To do it, let's calculate determinant of its matrix. Matrix has full rank iff its determinant is non-zero. Let's write a determinant as a sum over all permutations. $det A = \sum_{\pi} \prod_{i=1}^{n} A_{i \pi_{i}}$ If $A_{i \pi_{i}} \ne 0$ then we have edge $(i, \pi_{i})$ in our forest. Each permutation is a product of independent cycles. So to have non-zero product $\prod_{i=1}^{n} A_{i \pi_{i}}$ all the permutation cycles should be cycles in the forest. But forests have no cycles without repeating vertices! Well, actually they do: each edge generate one cycle of length $2$. And that's all, there are no other cycles in forest ($1$ vertex is not a cycle, because we don't have self-loops). To have non-zero product $\prod_{i=1}^{n} A_{i \pi_{i}}$ all cycles of permutation must have length $2$ and correspond to edges of forest. So we can divide all vertices in pairs, and in each pair there is an edge. That's the definition of perfect matching. Why can't they still result in zero sum? Because if there is a perfect matching in a forest then it is unique, so we actually have no more than one non-zero summand. OK, forest has full rank is equivalent to forest has perfect matching. Suppose that $m$ is the size of maximal matching of a forest. Then no its induced subgraph of size strictly greater than $2m$ can have perfect matching. And there is a subgraph of size exactly $2m$ which does have perfect matching: the ends of edges in maximal matching. Cool, we have proven the fact from the beginning. If you just want AC, continue reading from here. Now we have to calculate expected size of maximal matching. That sound much easier: we already have a linear DP which calculates maximal matching, and its values are exactly sizes of current maximal matching. To remind: $dp[v][taken]$ is a size of maximal matching in subtree rooted at $v$ where boolean flag $taken$ means did we already cover vertex $v$ or is it still free. All we have to do is to change the value stored in DP for expected value and also calculate probabilities to actually be in state with given flag $taken$. Complexity - $O(n)$.
|
[
"dp",
"graph matchings",
"math",
"trees"
] | 2,800
| null |
1068
|
A
|
Birthday
|
Ivan is collecting coins. There are only $N$ different collectible coins, Ivan has $K$ of them. He will be celebrating his birthday soon, so all his $M$ freinds decided to gift him coins. They all agreed to three terms:
- Everyone must gift as many coins as others.
- All coins given to Ivan must be different.
- Not less than $L$ coins from gifts altogether, must be new in Ivan's collection.
But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.
|
To get $L$ new coins irrespective of the Ivan's collection he must get not less than $L+K$ coins as a present. Therefore each friend should gift at least $X = \lceil \frac{L+K}{M} \rceil$ coins. But it may be not possible for all friends to gift $X$ coins if $X \cdot M > N$. Complexity is $O(1)$.
|
[
"math"
] | 1,400
| null |
1068
|
B
|
LCM
|
Ivan has number $b$. He is sorting through the numbers $a$ from $1$ to $10^{18}$, and for every $a$ writes $\frac{[a, \,\, b]}{a}$ on blackboard. Here $[a, \,\, b]$ stands for least common multiple of $a$ and $b$. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the board if he would finish the task. Help him to find the quantity of different numbers he would write on the board.
|
$\frac{[a, \,\, b]}{a} = \frac{b}{(a, \,\, b)}$, here $(a, \,\, b)$ is greatest common divisor. Let's see how many different values can have $c = (a, \,\, b)$. All values $c$ that divides $b$ are reachable if $a = c$ and every value of $(a, \,\, b)$ divides $b$. So answer is number of divisors of $b$. It can be calculated in $O(\sqrt{b})$ time.
|
[
"math",
"number theory"
] | 1,200
| null |
1068
|
C
|
Colored Rooks
|
Ivan is a novice painter. He has $n$ dyes of different colors. He also knows exactly $m$ pairs of colors which harmonize with each other.
Ivan also enjoy playing chess. He has $5000$ rooks. He wants to take $k$ rooks, paint each of them in one of $n$ colors and then place this $k$ rooks on a chessboard of size $10^{9} \times 10^{9}$.
Let's call the set of rooks on the board connected if from any rook we can get to any other rook in this set moving only through cells with rooks from this set. Assume that rooks can jump over other rooks, in other words a rook can go to any cell which shares vertical and to any cell which shares horizontal.
Ivan wants his arrangement of rooks to have following properties:
- For any color there is a rook of this color on a board;
- For any color the set of rooks of this color is connected;
- For any two different colors $a$ $b$ union of set of rooks of color $a$ and set of rooks of color $b$ is connected if and only if this two colors harmonize with each other.
Please help Ivan find such an arrangement.
|
Let's put rooks with color $i$ just on line number $i$. Then, obviously, for any color the set of rooks of this color would be connected. Let's put rooks on positions $(i, \,\, i)$ for $i$ from $1$ to $n$. After that for any color there is a rook of this color on a board and for any two different colors $a$ $b$ union of set of rooks of color $a$ and set of rooks of color $b$ wouldn't be connected. And for final step we can do the following for every pair of harmonizing colors $a$ $b$: let $j$ be index of first column without rooks, put rooks on cells ($j, \,\, a$) and ($j, \,\, b$). After that for colors $a$ $b$ union of set of rooks of color $a$ and set of rooks of color $b$ would become connected and for other pairs the connectedness doesn't change. Total number of rooks is $n + 2 \cdot m$.
|
[
"constructive algorithms",
"graphs"
] | 1,700
| null |
1071
|
E
|
Rain Protection
|
A lot of people dream of convertibles (also often called cabriolets). Some of convertibles, however, don't have roof at all, and are vulnerable to rain. This is why Melon Ask, the famous inventor, decided to create a rain protection mechanism for convertibles.
The workplace of the mechanism is a part of plane just above the driver. Its functional part consists of two rails with sliding endpoints of a piece of stretching rope. For the sake of simplicity we can consider this as a pair of parallel segments in a plane with the rope segment, whose endpoints we are free to choose as any points on these rails segments.
The algorithmic part of the mechanism detects each particular raindrop and predicts when and where it reaches the plane. At this exact moment the rope segment must contain the raindrop point (so the rope adsorbs the raindrop).
You are given the initial position of the rope endpoints and all information about raindrops. You are to choose the minimal possible speed $v$ of the endpoints sliding (both endpoints can slide in any direction along their segments independently of each other) in such a way that it is possible to catch all raindrops moving both endpoints with speed not greater than $v$, or find out that it's impossible no matter how high the speed is.
|
First, let's find out if we can catch all raindrops for a fixed speed $v$. Assume that the endpoints are at $(e_1, 0)$ and $(e_2, h)$ at any moment. Consider the point $(e_1, e_2)$ for this state (we call it the state point for this state). From now on we work with these points. We know that this state point can move with speed at most $v$ in both directions independently, that is, if the state point is $(x, y)$ at the moment $t$, then it'll be in $[x - v\cdot\text{d}t, x + v\cdot\text{d}t]\times[y - v\cdot\text{d}t, y + v\cdot\text{d}t]$ at the moment $t + \text{d}t$. It turns out that for each $i$ one of the following takes place: we cannot catch raindrops from $1$ to $i$; we can catch these raindrops and there is exactly one possible option for the state point at the moment $t_i$; we can catch these raindrops and there is a segment on the plane such that the state point at the moment $t_i$ can be in any point of this segment and nowhere else. Indeed, we prove this by induction. Its basis for $t_0 = 0$ is trivial. Let's prove its step. If we cannot catch raindrops from $1$ to $i$ then we cannot catch all raindrops from $1$ to $i + 1$. If there is some segment where the state point can be at $t_i$ (possibly a segment of length $0$) then at the moment $t_{i+1}$ the state point can be anywhere inside the convex hull of the union of two squares. The squares are $[x - v\cdot\text{d}t, x + v\cdot\text{d}t]\times[y - v\cdot\text{d}t, y + v\cdot\text{d}t]$ for the endpoints $(x, y)$ of the segment at $t_i$, and here $\text{d}t$ is $t_{i + 1} - t_i$.But we also know that the rope must contain one particular point at the moment $t_{i+1}$, which can be expressed as a linear equation of the state point at the moment $t_{i+1}$. So to obtain the required segment for $t_{i+1}$ one should intersect a line with a convex hull of $8$ points (which is in fact no more than a hexagon). However, it's not all: the endpoints of the rope mustn't leave the rails which means that the convex hull should be first intersected with the rectangle $[0, w]\times[0, w]$. However, it can be done after intersecting with the required line. But we also know that the rope must contain one particular point at the moment $t_{i+1}$, which can be expressed as a linear equation of the state point at the moment $t_{i+1}$. So to obtain the required segment for $t_{i+1}$ one should intersect a line with a convex hull of $8$ points (which is in fact no more than a hexagon). However, it's not all: the endpoints of the rope mustn't leave the rails which means that the convex hull should be first intersected with the rectangle $[0, w]\times[0, w]$. However, it can be done after intersecting with the required line. So the solution now is the following: First we check if the answer is $-1$. This is the case when there is a triple of non-collinear raindrop points which should be on the rope simultaneously or there is a raindrop which is not on the rope at the moment $0$, while it should be. The simplest way to check it is to check if we can catch all raindrops with speed $w$. First, it involves no case handling; second, we will use this function later anyway. After this we run a binary search to find the minimal possible value for speed in such a way that it's possible to catch all the raindrops. That's the idea of the solution. Now let's consider precision issues. The explanation below contains some notions which may be new for a particular reader. Please don't be afraid of them, I explain what they mean right after introducing them. I refer to them by their names first for readers familiar with these notions to get the point faster and maybe skip the explanation which follows. For anyone who doesn't want to read the full proof and wants to know the summary: long double precision should be enough to get AC with the solution above (handling lines intersections properly). Define a function $f_i(v)$ as the $\ell_{\infty}$-diameter of the set of possible locations of the state point at the moment $t_i$ for the speed $v$, that is, $f_i(v) = 0$ if this set is empty or consists of a single point; $f_i(v) = \max\left(|x_1 - x_2|, |y_1 - y_2|\right)$ if this set is a segment between $(x_1, y_1)$ and $(x_2, y_2)$. In other words, every time we calculate the length of any segment, we do it in this metric, since it'll be convenient for our purposes. Let $\hat{v}$ be the correct answer, and let $\varepsilon$ be a sufficiently small positive number (but still much bigger than the machine epsilon, of course). One can see that all $t_i$-s can be divided into two groups which differ a lot by their meaning: those for which we must catch one raindrop at this moment (or many equal raindrops, which doesn't matter), those for which we must catch more than one raindrop at this moment. For the first ones we basically need to intersect a polygon with a line, but for the second ones the state point at $t_i$ can be determined and doesn't depend on the speed (or such $t_i$-s force our algorithm to tell that the goal is impossible in the very beginning). Let's call the raindrops with $t_i$ of the first type simple, and the others complicated. Let's prove the following lemmas: Lemma 1a. Let $i$ be an index of a simple raindrop. For $v = \hat{v} + \varepsilon$ each $f_i(v)$ is at least $\varepsilon$. Lemma 1b. Let $i$ be an index of a complicated raindrop. For $v = \hat{v} + \varepsilon$ the corresponding state point position at the moment $t_i$ is at least $\varepsilon$ away from the border of a polygon before intersecting with $[0, w]\times[0, w]$. Lemma 2. Let $idx$ be the index of the first raindrop we cannot catch for a value of speed which is very close to $\hat{v}$ but is less than it. Then for $v = \hat{v} - \varepsilon$ either our algorithm halts earlier than it handles the $idx$-th raindrop, or the corresponding line to this raindrop (or the corresponding point if the raindrop is complicated) is at least $\varepsilon$ away from the corresponding state points polygon (again, in $\ell_{\infty}$ metric). One can see that proving these lemmas is sufficient to validate the solution. Indeed, comparing all intersections with quite good precision will move the binary search borders into the $(\hat{v} - \varepsilon, \hat{v} + \varepsilon)$ interval which is enough to stop for some $\varepsilon$. Proof of lemma 1 (both variations). Fix $i$. We know that the $(i-1)$-th set $S_{i-1}(v)$ of possible state points for $v = \hat{v}$ is not empty (from the definition of $\hat{v}$). It's clear that the $(i-1)$-th set for $v = \hat{v} + \varepsilon$ is a superset of $S_{i-1}(\hat{v})$, because we can move no faster than with the speed of $\hat{v} < \hat{v} + \varepsilon$. To get $S_i$, we move from $S_{i-1}$ no more than $(t_i - t_{i-1})(\hat{v} + \varepsilon) \le (t_i - t_{i-1})\hat{v} + \varepsilon$. This finishes the proof of 1b. Since $S_i(\hat{v})$ is also not empty, $S_i(\hat{v} + \varepsilon)$ is at least the segment $S_i(\hat{v})$ plus all the points on the corresponding line at the distance no more than $\varepsilon$, that is, at least $\varepsilon$ longer than $S_i(\hat{v})$, hence is at least $\varepsilon$ long, qed. Proof of lemma 2. Assume our algorithm made at least $idx$ iterations. Consider the corresponding polygon at the moment $t_{idx}$. We know that for $v = \hat{v}$ this polygon intersects the required line/point, but its interior doesn't. That means that each point of the possible set of state points at the moment isn't inside the polygon. That means that if we reduce $v$ by $\varepsilon$ then the distance from every point of this set to the polygon is at least $\varepsilon$, qed. To summarize, the only precision issue we can meet is when we intersect two or more lines for complicated raindrops. This part can be implemented in integers, but let's dive into this anyway. One can see that catching raindrop at $(x, y)$ means that or Since the coefficients of this line equation are of order $h$, the coordinates of its solution are some rationals with the denominator of order $1/h^2$. If we then want to check if such point belongs to another line, we want to compare some integer divided by another integer which is $\le h^2$ with the third integer, so we need an epsilon less than $1/h^2$.
|
[
"binary search",
"geometry"
] | 3,500
| null |
1073
|
A
|
Diverse Substring
|
You are given a string $s$, consisting of $n$ lowercase Latin letters.
A substring of string $s$ is a continuous segment of letters from $s$. For example, "defor" is a substring of "codeforces" and "fors" is not.
The length of the substring is the number of letters in it.
Let's call some string of length $n$ diverse if and only if there is no letter to appear strictly more than $\frac n 2$ times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.
Your task is to find \textbf{any} diverse substring of string $s$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.
|
Notice that the string of two distinct letter is already diverse. That implies that the answer is "NO" if and only if all the letters in the string are the same. Otherwise you can check all pairs of adjacent letters in $O(n)$. Overall complexity: $O(n)$.
|
[
"implementation",
"strings"
] | 1,000
|
n = int(input())
s = input()
for i in range(n - 1):
if (s[i] != s[i + 1]):
print("YES")
print(s[i], s[i + 1], sep="")
exit(0)
print("NO")
|
1073
|
B
|
Vasya and Books
|
Vasya has got $n$ books, numbered from $1$ to $n$, arranged in a stack. The topmost book has number $a_1$, the next one — $a_2$, and so on. The book at the bottom of the stack has number $a_n$. \textbf{All numbers are distinct}.
Vasya wants to move all the books to his backpack in $n$ steps. During $i$-th step he wants to move the book number $b_i$ into his backpack. If the book with number $b_i$ is in the stack, he takes this book and all the books \textbf{above} the book $b_i$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $[1, 2, 3]$ (book $1$ is the topmost), and Vasya moves the books in the order $[2, 1, 3]$, then during the first step he will move two books ($1$ and $2$), during the second step he will do nothing (since book $1$ is already in the backpack), and during the third step — one book (the book number $3$). \textbf{Note that $b_1, b_2, \dots, b_n$ are distinct.}
Help Vasya! Tell him the number of books he will put into his backpack during each step.
|
Let's maintain the pointer $pos$ to the topmost non-deleted book and whether each book whether is removed from the stack or not. Initially, all books are in a stack, and $pos$ is 0 (if we store the array 0-indexed). We will process the array $B$ in the order $b_1, b_2, \dots b_n$. If the current book $b_i$ is removed from the stack, then the answer for it is zero. Otherwise, we will increment the pointer $pos$ until the equality $a_{pos} = b_i$ is satisfied, while marking all the intermediate books in the array $u$. After that, the answer for the book $b_i$ will be the number of marked books in the $u$ array (including itself). Since the pointer $pos$ shifts $n$ times at total, we get a solution with an $O(n)$ complexity.
|
[
"implementation",
"math"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 9;
int n;
int a[N];
int b[N];
bool u[N];
int main() {
// freopen("input.txt", "r", stdin);
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%d", a + i);
}
for(int i = 0; i < n; ++i){
scanf("%d", b + i);
}
int pos = 0;
for(int i = 0; i < n; ++i){
int x = b[i];
if(u[x]){
printf("0 ");
continue;
}
int cnt = 0;
while(true){
++cnt;
u[a[pos]] = true;
if(a[pos] == x) break;
++pos;
}
++pos;
printf("%d ", cnt);
}
puts("");
return 0;
}
|
1073
|
C
|
Vasya and Robot
|
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $(0, 0)$. Robot can perform the following four kinds of operations:
- U — move from $(x, y)$ to $(x, y + 1)$;
- D — move from $(x, y)$ to $(x, y - 1)$;
- L — move from $(x, y)$ to $(x - 1, y)$;
- R — move from $(x, y)$ to $(x + 1, y)$.
Vasya also has got a sequence of $n$ operations. Vasya wants to modify this sequence so after performing it the robot will end up in $(x, y)$.
Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: $maxID - minID + 1$, where $maxID$ is the maximum index of a changed operation, and $minID$ is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices $2$, $5$ and $7$ are changed, so the length of changed subsegment is $7 - 2 + 1 = 6$. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is $1$.
\textbf{If there are no changes, then the length of changed subsegment is $0$. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.}
Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from $(0, 0)$ to $(x, y)$, or tell him that it's impossible.
|
Denote $d = |x| + |y|$. If $d > n$, then the answer is -1, since the robot will not have the time to reach $(x, y)$ cell in $n$ steps. Also, if $d$ and $n$ have different parity, then the answer is also -1, as in one move the robot changes the parity of the sum of its coordinates. In all other cases, the answer exists. Let's use binary search to solve this problem. Consider all segments of length $len$. For a fixed length of the segment $len$, let's iterate over the position of the beginning of the segment $l$. At the same time, we will maintain the cell that the robot will stop at if it execute all commands, except commands with indices $l, l + 1, \dots, l + len - 1$. We denote this position as $(x_0, y_0)$. We also calculate the distances from the cell $(x_0, y_0)$ to the cell $(x, y)$ - the value $d_0 = |x - x_0| + |y - y_0|$. If there is at least one position of the beginning of the segment for which $d_0 \le len$, then we can change the segment of length $len$ so that the robot comes to the $(x, y)$ cell, otherwise it can't.
|
[
"binary search",
"two pointers"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
const int N = int(1e5) + 9;
string s;
int n;
int x, y;
void upd(pair<int, int> &pos, char mv, int d){
if(mv == 'U')
pos.second += d;
if(mv == 'D')
pos.second -= d;
if(mv == 'L')
pos.first -= d;
if(mv == 'R')
pos.first += d;
}
bool can(pair<int, int> u, pair<int, int> v, int len){
int d = abs(u.first - v.first) + abs(u.second - v.second);
if(d % 2 != len % 2) return false;
return len >= d;
}
bool ok(int len){
pair<int, int> pos = make_pair(0, 0);
for(int i = len; i < n; ++i)
upd(pos, s[i], 1);
int l = 0, r = len;
while(true){
if(can(pos, make_pair(x, y), len))
return true;
if(r == n) break;
upd(pos, s[l++], 1);
upd(pos, s[r++], -1);
}
return false;
}
int main() {
//freopen("input.txt", "r", stdin);
cin >> n;
cin >> s;
cin >> x >> y;
if(!ok(n)){
puts("-1");
return 0;
}
int l = -1, r = n;
while(r - l > 1){
int mid = (l + r) / 2;
if(ok(mid)) r = mid;
else l = mid;
}
cout << r << endl;
return 0;
}
|
1073
|
D
|
Berland Fair
|
XXI Berland Annual Fair is coming really soon! Traditionally fair consists of $n$ booths, arranged in a circle. The booths are numbered $1$ through $n$ clockwise with $n$ being adjacent to $1$. The $i$-th booths sells some candies for the price of $a_i$ burles per item. Each booth has an unlimited supply of candies.
Polycarp has decided to spend at most $T$ burles at the fair. However, he has some plan in mind for his path across the booths:
- at first, he visits booth number $1$;
- if he has enough burles to buy \textbf{exactly one} candy from the current booth, then he buys it immediately;
- then he proceeds to the next booth in the clockwise order (regardless of if he bought a candy or not).
Polycarp's money is finite, thus the process will end once he can no longer buy candy at any booth.
Calculate the number of candies Polycarp will buy.
|
Let's code the following process. Go one circle across the booths, calculate the total cost $C$ of sweets bought and the number $S$ of sweets bought. Now you can decrease you money down to $T = T~mod~C$ and add $S \cdot (T~div~C)$ to answer. It represents that you went maximum number of such circles. The later circles will have smaller cost. Let's continue this process until $T$ becomes smaller than the minimum priced sweet. The number of operations made is $O(\log T)$. Let $T_{cur}$ be the amount of money before some operation, $C_{cur}$ be the total cost of sweets bought on that operation and $T_{new} = T_{cur}~mod~C_{cur}$. $T_{new}$ is actually smaller than $C_{cur}$ (that's how modulo works) and smaller than $T_{cur} - C_{cur}$ (that's also how modulo works). And these inequalities imply that $T_{new} < \frac{T_{cur}}{2}$. That leads to about $O(\log T)$ steps to reach the minimal price. Overall complexity: $O(n \log T)$.
|
[
"binary search",
"brute force",
"data structures",
"greedy"
] | 1,700
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 200 * 1000 + 13;
typedef long long li;
int n;
int a[N];
void get(li T, li& pr, li& cnt){
pr = 0, cnt = 0;
forn(i, n){
if (T >= a[i]){
T -= a[i];
pr += a[i];
++cnt;
}
}
}
int main() {
li T;
scanf("%d%lld", &n, &T);
forn(i, n)
scanf("%d", &a[i]);
int mn = *min_element(a, a + n);
li ans = 0;
while (T >= mn){
li pr, cnt;
get(T, pr, cnt);
ans += cnt * (T / pr);
T %= pr;
}
printf("%lld\n", ans);
return 0;
}
|
1073
|
E
|
Segment Sum
|
You are given two integers $l$ and $r$ ($l \le r$). Your task is to calculate the sum of numbers from $l$ to $r$ (including $l$ and $r$) such that each number contains \textbf{at most} $k$ different digits, and print this sum modulo $998244353$.
For example, if $k = 1$ then you have to calculate all numbers from $l$ to $r$ such that each number is formed using only one digit. For $l = 10, r = 50$ the answer is $11 + 22 + 33 + 44 = 110$.
|
Let's calculate the answer as the sum of suitable numbers in range $[1; r]$ minus the sum of suitable numbers in range $[1; l - 1]$. Now our problem is to calculate the sum of suitable numbers in range $[1; n]$. The main approach for this problem is digit DP. Let's calculate two dynamic programmings $dp_{pos, mask, f}$ and $dps_{pos, mask, f}$. $pos$ means that now we are at the $pos$-th digit of the number $n$ (at the digit corresponding to $10^{len - pos - 1}$, where $len$ is the decimal length of a number), $mask$ is a binary mask describing digits we already use and $f$ equals $1$ if the current prefix of number we trying to obtain is the same as the prefix of number $n$ (otherwise $f$ equals $0$). So what means $dp_{pos, mask, f}$? It means the count of numbers (in general, not numbers but their prefixes) in range $[1; n]$ of length exactly $|n|$ without leading zeroes corresponding to this state. So what the point of this DP? Its point is helping us to calculate the main DP, $dps_{pos, mask, f}$, which means the sum of numbers (in general, not numbers but their prefixes) in range $[1; n]$ of length exactly $|n|$ without leading zeroes corresponding to this state. How do we calculate the answer? Firstly, let $len$ be the length of $n$. Let $calc(n)$ be the function calculating the sum of numbers from $1$ to $n$ containing at most $k$ different digits. How to calculate it? Let $calcdp(x)$ be the sum of numbers from $1$ to $x$ containing at most $k$ different digits and having length exactly $|x|$. Then $calc(n)$ seems to be pretty easy: for each length $i$ from $1$ to $len-1$ add to the answer $calcdp(10^i - 1)$. And the last step is to add to the answer $calcdp(n)$. How to calculate dynamic programmings? Initially, all states are zeroes (excluding $dp_{0, 0, 1}$, which is $1$). Firstly, let's calculate $dp$. After calculating it we can calculate $dps$ in almost the same way. Let's iterate over all possible lengths and over all possible masks. Let the current state is $dp_{pos, mask, 0}$. Then let's iterate over next digit we will place in this number and place it. If $pos = 0$ then $dig = 1 \dots 9$ otherwise $dig = 0 \dots 9$. The transition is pretty easy: $dp_{pos + 1, mask | 2^{dig}, 0} += dp_{pos, mask, 0}$. There $|$ is the bitwise OR operation. For $f = 1$ transitions are almost the same expect the restrictions on digit we place and the state we update. If we now at the position $pos$ with mask $mask$ and $f = 1$ then the current digit of $n$ is $n_{pos}$. Then let's iterate over next digit: $dig = 1 \dots n_{pos}$ if $pos = 0$ otherwise $dig = 0 \dots n_{pos}$. The transition is also easy: $dp_{pos + 1, mask | 2^{dig}, dig = n_{pos}} += dp_{pos, mask, f}$. After calculating the previous DP we can calculate $dps$. All the process is the same as in the previous dynamic programming expect the value we will add in transitions. In the previous DP this value was equal $dp_{pos, mask, f}$, in the current DP this value equals to $val = dps_{pos, mask, f} + dig \cdot 10^{len - pos - 1} \cdot dp_{pos, mask, f}$. Don't forget to calculate it modulo $998244353$! So after calculating all the values of DPs, what is the answer for $calcdp(n)$? It is $\sum\limits_{mask = 0}^{2^{10} - 1} dps_{|n|, mask, 0} + dps_{|n|, mask, 1}$ for all masks with at most $k$ bits. I'm pretty sure that there is another way to avoid leading zeroes in calculating these DPs but this one is very straight-forward and simple.
|
[
"bitmasks",
"combinatorics",
"dp",
"math"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<long long, int> pt;
const int N = 20;
const int M = 1 << 10;
const int MOD = 998244353;
int k;
int pw10[N];
int bitCnt[M];
pt dp[N][M][2];
int add(int a, int b) {
a += b;
if (a >= MOD) a -= MOD;
if (a < 0) a += MOD;
return a;
}
int mul(int a, int b) {
return a * 1ll * b % MOD;
}
int calc(const string &s) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
dp[i][j][0] = dp[i][j][1] = { 0ll, 0 };
}
}
int len = s.size();
dp[0][0][1] = { 1ll, 0 };
for (int i = 0; i < len; ++i) {
int cdig = s[i] - '0';
for (int mask = 0; mask < M; ++mask) {
if (dp[i][mask][0].x == 0 && dp[i][mask][1].x == 0) continue;
for (int dig = (i == 0); dig <= 9; ++dig) {
int nmask = mask | (1 << dig);
long long cnt = dp[i][mask][0].x;
int sum = add(dp[i][mask][0].y, mul(dig, mul(pw10[len - i - 1], cnt % MOD)));
dp[i + 1][nmask][0].x += cnt;
dp[i + 1][nmask][0].y = add(dp[i + 1][nmask][0].y, sum);
}
for (int dig = (i == 0); dig <= cdig; ++dig) {
int nmask = mask | (1 << dig);
long long cnt = dp[i][mask][1].x;
int sum = add(dp[i][mask][1].y, mul(dig, mul(pw10[len - i - 1], cnt % MOD)));
dp[i + 1][nmask][dig == cdig].x += cnt;
dp[i + 1][nmask][dig == cdig].y = add(dp[i + 1][nmask][dig == cdig].y, sum);
}
}
}
int ans = 0;
for (int mask = 0; mask < M; ++mask) {
if (bitCnt[mask] > k) continue;
ans = add(ans, dp[len][mask][0].y);
ans = add(ans, dp[len][mask][1].y);
}
return ans;
}
int calc(long long n) {
int len = to_string(n).size();
int ans = 0;
for (int l = 1; l < len; ++l) {
ans = add(ans, calc(string(l, '9')));
}
ans = add(ans, calc(to_string(n)));
return ans;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
pw10[0] = 1;
for (int i = 1; i < N; ++i) {
pw10[i] = mul(pw10[i - 1], 10);
}
for (int i = 0; i < M; ++i) {
bitCnt[i] = __builtin_popcount(i);
}
long long l, r;
cin >> l >> r >> k;
int ans = add(calc(r), -calc(l - 1));
cout << ans << endl;
return 0;
}
|
1073
|
F
|
Choosing Two Paths
|
You are given an undirected unweighted tree consisting of $n$ vertices.
An undirected tree is a connected undirected graph with $n - 1$ edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices \textbf{should be distinct}) $(x_1, y_1)$ and $(x_2, y_2)$ in such a way that neither $x_1$ nor $y_1$ belong to the simple path from $x_2$ to $y_2$ and vice versa (neither $x_2$ nor $y_2$ should not belong to the simple path from $x_1$ to $y_1$).
\textbf{It is guaranteed that it is possible to choose such pairs for the given tree.}
Among all possible ways to choose such pairs you have to choose one with the \textbf{maximum number of common vertices} between paths from $x_1$ to $y_1$ and from $x_2$ to $y_2$. And among all such pairs you have to choose one with the \textbf{maximum total length} of these two paths.
\textbf{It is guaranteed that the answer with at least two common vertices exists for the given tree.}
The length of the path is the number of edges in it.
The simple path is the path that visits each vertex at most once.
|
Firstly, let's call a path from $u$ to $v$ good, if $u$ is a leaf, $v$ is a vertex of degree at least $3$ (the number of their neighbors is at least $3$) and there are no other vertices of degree at least $3$ on this path expect the vertex $v$. The first step of the solution is to remove all the good paths from $u$ to $v$ (but we should not remove the vertex $v$) and remember for each vertex $v$ the sum of two maximum lengths of good paths which end in the vertex $v$. Let this value for the vertex $v$ be $val_v$. For example, if for some vertex $v$ there are $3$ good paths with end in it of lengths $2$, $3$ and $5$ correspondingly, then $val_v$ will be $5 + 3 = 8$. Okay, it is easy to see that the maximum intersection of two paths in the answer will be equal to the length of the diameter of the obtained tree. But we can not take any diameter of this tree and call it the answer because of the second constraint: we need to find some diameter from $x$ to $y$ such that the sum $val_x + val_y$ is maximum possible. How do we do that? There is such an awesome (and well-known) fact that the center of a tree belongs to all diameters of this tree. Let's root the tree by the center of a tree (if the length of the diameter is odd (the center of a tree is an edge) then let's root the tree by any end of this edge, it does not matter). There is one case when the length of the diameter is $1$ but it is pretty trivial to handle it. Now our problem is to find two neighbors of the root of the new tree such that in their subtrees are vertices which form some diameter of this tree and the sum of values of these vertices is maximum possible. Let's calculate the vertex with the maximum distance from a root (and with the maximum possible $val_v$ for equals distances) by simple DFS for each neighbor of a root. It can be done in $O(n)$ and the last part is to find two maximums of this list, it also can be done in $O(n)$ or $O(n \log n)$, depends on implementation.
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define size(a) int((a).size())
typedef pair<int, int> pt;
const int N = 200 * 1000 + 11;
int n;
vector<int> g[N];
int p[N];
int dist[N];
bool bad[N];
int value[N];
pt res[N];
vector<pt> best[N];
void dfs(int v, int par = -1, int d = 0) {
p[v] = par;
dist[v] = d;
for (auto to : g[v]) {
if (to == par) {
continue;
}
dfs(to, v, d + 1);
}
}
int getFarthest(int v) {
dfs(v);
int res = v;
for (int i = 0; i < n; ++i) {
if (bad[i]) {
continue;
}
if (dist[res] < dist[i]) {
res = i;
}
}
return res;
}
pt get(int v) {
return { dist[v], value[v] };
}
int getBetter(int v, int u) {
if (get(v) > get(u)) {
return v;
}
return u;
}
int getBest(int v, int par) {
int res = v;
for (auto to : g[v]) {
if (to == par || bad[to]) {
continue;
}
res = getBetter(res, getBest(to, v));
}
return res;
}
pt calc(int v) {
dfs(v);
vector<int> ch;
for (auto to : g[v]) {
if (!bad[to]) {
ch.push_back(to);
}
}
if (size(ch) == 1) {
return { v, ch[0] };
}
vector<int> pref(size(ch));
vector<int> suf(size(ch));
vector<int> best(size(ch));
for (int i = 0; i < size(ch); ++i) {
int to = ch[i];
best[i] = pref[i] = suf[i] = getBest(to, v);
}
for (int i = 1; i < size(ch); ++i) {
pref[i] = getBetter(pref[i], pref[i - 1]);
suf[size(ch) - i - 1] = getBetter(suf[size(ch) - i - 1], suf[size(ch) - i]);
}
pt ans = { -1, -1 };
pt res = { 0, 0 };
for (int i = 0; i < size(ch); ++i) {
int bst = -1;
if (i == 0) {
bst = suf[i + 1];
} else if (i + 1 == size(ch)) {
bst = pref[i - 1];
} else {
bst = getBetter(pref[i - 1], suf[i + 1]);
}
pt curRes = { dist[bst] + dist[best[i]], value[bst] + value[best[i]] };
if (res < curRes) {
res = curRes;
ans = { best[i], bst };
}
}
return ans;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n;
for (int i = 0; i < n - 1; ++i) {
int x, y;
cin >> x >> y;
--x, --y;
g[x].push_back(y);
g[y].push_back(x);
}
int root = -1;
for (int i = 0; i < n; ++i) {
if (size(g[i]) > 2) {
root = i;
dfs(i);
break;
}
}
for (int i = 0; i < n; ++i) {
if (size(g[i]) != 1) {
continue;
}
int v = i;
while (size(g[v]) < 3) {
bad[v] = true;
v = p[v];
}
best[v].push_back({dist[i] - dist[v], i});
}
for (int i = 0; i < n; ++i) {
if (size(best[i]) >= 2) {
sort(best[i].rbegin(), best[i].rend());
value[i] = best[i][0].first + best[i][1].first;
res[i] = { best[i][0].second, best[i][1].second };
}
}
int u = getFarthest(root);
int v = getFarthest(u);
vector<int> path;
while (v != u) {
path.push_back(v);
v = p[v];
}
path.push_back(u);
pt ans = calc(path[size(path) / 2]);
printf("%d %d\n", res[ans.x].x + 1, res[ans.y].x + 1);
printf("%d %d\n", res[ans.x].y + 1, res[ans.y].y + 1);
return 0;
}
|
1073
|
G
|
Yet Another LCP Problem
|
Let $\text{LCP}(s, t)$ be the length of the longest common prefix of strings $s$ and $t$. Also let $s[x \dots y]$ be the substring of $s$ from index $x$ to index $y$ (inclusive). For example, if $s = $ "abcde", then $s[1 \dots 3] =$ "abc", $s[2 \dots 5] =$ "bcde".
You are given a string $s$ of length $n$ and $q$ queries. Each query is a pair of integer sets $a_1, a_2, \dots, a_k$ and $b_1, b_2, \dots, b_l$. Calculate $\sum\limits_{i = 1}^{i = k} \sum\limits_{j = 1}^{j = l}{\text{LCP}(s[a_i \dots n], s[b_j \dots n])}$ for each query.
|
At first, implement your favourite string suffix structure for comparing pair of suffixes lexicographically fast enough. For example, it's a Suffix Array + linear LCP + Sparse Table. Now we can compare two suffixes $i$ and $j$ by finding $l = lcp(i, j)$ and comparing $s[i + l]$ with $s[j + l]$. We will process queries online. Let current query be a pair of arrays $a$ ($|a| = k$) and $b$ ($|b| = l$). We will calculate answer in two parts: To calculate the first sum we can sort all $c = a + b$ suffixes in lexicographical order and maintain some information for prefixes of $c$. What information we need to maintain? We need some Data Structure which will hold $lcp$ of suffixes from $a$. When we process some $c_i = b_j$ we need just a total sum of all $lcp$ in the DS. If $c_i = a_j$, we should add to the DS length of $a_j$-th suffix. And when we move from $c_i$ to $c_{i + 1}$ we must recalculate some $lcp$. Since $c$ is sorted, all we need is to set $lcp_k = min(lcp_k, lcp(s[c_i \dots n], s[c_{i + 1} \dots n]))$. In fact, this Data Structure is just a $map$. In this $map$ we will hold for each length $l$ number of suffixes with $lcp = l$ (we will hold only non-zero values). When we should add some suffix $a_j$, we manually increase some value by one. Setting $min$ with $v = lcp(s[c_i \dots n], s[c_{i + 1} \dots n])$ can be done with decreasing maximum in $map$ while its more than $v$. It can be proven, that there will be $O(|a| + |b|)$ operations with $map$ for one query. The total sum can be maintained in some global variable, which will be recalculated each time $map$ changes. To calculate the second sum we can just reverse $c$ and run the same algorithm. So total complexity is $O(n \log^2{n} + (\sum\limits_{i = 1}^{i = q}{k_i} + \sum\limits_{i = 1}^{i = q}{l_i}) \log{n})$.
|
[
"data structures",
"string suffix structures"
] | 2,600
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
template<class A, class B> ostream& operator <<(ostream &out, const pair<A, B> &p) {
return out << "(" << p.x << ", " << p.y << ")";
}
template<class A> ostream& operator <<(ostream &out, const vector<A> &v) {
out << "[";
fore(i, 0, sz(v)) {
if(i) out << ", ";
out << v[i];
}
return out << "]";
}
const int N = 200 * 1000 + 555;
const int LOGN = 18;
int n, q;
char s[N];
bool read() {
if(!(cin >> n >> q))
return false;
assert(scanf("%s", s) == 1);
return true;
}
int c[N], id[N], lcp[N];
int mn[LOGN][N];
int lg2[N];
void buildSuffArray() {
s[n++] = '$';
for(int l = 1; l < 2 * n; l <<= 1) {
vector< pair<pt, int> > d;
fore(i, 0, n)
d.emplace_back(l == 1 ? pt(s[i], 0) : pt(c[i], c[(i + (l >> 1)) % n]), i);
stable_sort(d.begin(), d.end());
c[d[0].y] = 0;
fore(i, 1, n)
c[d[i].y] = c[d[i - 1].y] + (d[i].x != d[i - 1].x);
if(c[d.back().y] == n - 1)
break;
}
fore(i, 0, n)
id[c[i]] = i;
int l = 0;
fore(i, 0, n) {
if(c[i] == n - 1)
continue;
l = max(0, l - 1);
int j = id[c[i] + 1];
while(i + l < n && j + l < n && s[i + l] == s[j + l])
l++;
lcp[c[i]] = l;
}
n--;
lg2[0] = lg2[1] = 0;
fore(i, 2, N) {
lg2[i] = lg2[i - 1];
if((1 << (lg2[i] + 1)) <= i)
lg2[i]++;
}
fore(i, 0, n)
mn[0][i] = lcp[i];
fore(pw, 1, LOGN) fore(i, 0, n) {
mn[pw][i] = mn[pw - 1][i];
if(i + (1 << (pw - 1)) < n)
mn[pw][i] = min(mn[pw][i], mn[pw - 1][i + (1 << (pw - 1))]);
}
}
int getMin(int l, int r) {
int ln = lg2[r - l];
return min(mn[ln][l], mn[ln][r - (1 << ln)]);
}
int getLCP(int i, int j) {
if(i == j) return n - i;
i = c[i], j = c[j];
return getMin(min(i, j), max(i, j));
}
bool cmp(const pt &a, const pt &b) {
if(a.x == b.x)
return a.y < b.y;
int l = getLCP(a.x, b.x);
return s[a.x + l] < s[b.x + l];
}
void solve() {
buildSuffArray();
fore(_, 0, q) {
int k, l;
assert(scanf("%d%d", &k, &l) == 2);
vector<int> a(k), b(l);
fore(i, 0, k)
assert(scanf("%d", &a[i]) == 1), a[i]--;
fore(j, 0, l)
assert(scanf("%d", &b[j]) == 1), b[j]--;
li ans = 0;
vector<pt> c;
for(auto v : a)
c.emplace_back(v, 1);
for(auto v : b)
c.emplace_back(v, 0);
sort(c.begin(), c.end(), cmp);
fore(k, 0, 2) {
li sum = 0;
map<int, int> cnt;
fore(i, 0, sz(c)) {
int id = c[i].x, tp = c[i].y;
if(tp == 0)
ans += sum;
else {
cnt[n - id]++;
sum += (n - id);
}
if(i + 1 < sz(c)) {
int len = getLCP(c[i].x, c[i + 1].x);
while(!cnt.empty()) {
auto it = --cnt.end();
if(it->x <= len)
break;
sum -= it->x * 1ll * it->y;
cnt[len] += it->y;
sum += it->y * 1ll * len;
cnt.erase(it);
}
}
}
reverse(c.begin(), c.end());
}
printf("%lld\n", ans);
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
#endif
}
return 0;
}
|
1075
|
A
|
The King's Race
|
On a chessboard with a width of $n$ and a height of $n$, rows are numbered from bottom to top from $1$ to $n$, columns are numbered from left to right from $1$ to $n$. Therefore, for each cell of the chessboard, you can assign the coordinates $(r,c)$, where $r$ is the number of the row, and $c$ is the number of the column.
The white king has been sitting in a cell with $(1,1)$ coordinates for a thousand years, while the black king has been sitting in a cell with $(n,n)$ coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates $(x,y)$...
Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:
As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, \textbf{kings can stand in adjacent cells or even in the same cell at the same time}.
The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates $(x,y)$ first will win.
Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the $(a,b)$ cell, then in one move he can move from $(a,b)$ to the cells $(a + 1,b)$, $(a - 1,b)$, $(a,b + 1)$, $(a,b - 1)$, $(a + 1,b - 1)$, $(a + 1,b + 1)$, $(a - 1,b - 1)$, or $(a - 1,b + 1)$. Going outside of the field is prohibited.
Determine the color of the king, who will reach the cell with the coordinates $(x,y)$ first, if the white king moves first.
|
Let's find the minimum time needed for the white king to reach the coin. It is obvious that it is always optimal to move only towards the coin. In case of white king it means that we should move only up, right or up-right diagonally. During one move we can only add $1$ or $0$ to any of our coordinates (or to both of them), it means that the length of the optimal path can not be smaller than $max(x-1,y-1)$. Let's show that we can reach the coin with $max(x-1,y-1)$ moves. First step. Let $z$ be equal to $min(x,y)$. The king does $z-1$ up-right moves, so after that the king will be in the cell $(z,z)$. Second step. Let's assume that $x \le y$ (the case when $x > y$ is proved in a similar way). So $z = x$. It means that the king is in the cell $(x,x)$. Now the king can do $y-x$ up moves, after which he would be in the cell $(x,y)$. It took him $(x-1)+(y-x)=y-1$ moves to reach the coin. If $x$ was greater than $y$ he would need $x-1$ moves (could be proved the same way). So now we proved that it takes $max(x-1,y-1)$ moves for the white king to reach the coin. In the same way we can prove that it takes $max(n-x,n-y)$ steps for the black king to reach the coin. The king, which is closer to the coin, wins. If the distances is equal, than the white king wins, because he moves first. Final description of the algorithm: If $max(n-x,n-y)<max(x-1,y-1)$ then the answer is "Black", otherwise the answer is "White". It is also can be proven that instead of comparing minimal distances between the coin and the kings we can compare manhattan distances between them. I will leave the proof as homework task.
|
[
"implementation",
"math"
] | 800
| null |
1075
|
B
|
Taxi drivers and Lyft
|
Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.
Lyft has become so popular so that it is now used by all $m$ taxi drivers in the city, who every day transport the rest of the city residents — $n$ riders.
Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).
The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.
But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $i$ the number $a_{i}$ — the number of riders that would call the $i$-th taxi driver when all drivers and riders are at their home?
The taxi driver can neither transport himself nor other taxi drivers.
|
Let's find for each rider the taxi driver that will get his call. To do this we can find for each rider the nearest taxi driver at right and the nearest taxi driver at left. Let's define the nearest taxi driver at left for $i$-th citizen as $l_i$ and at the right as $r_i$. The computations can be done with the following algorithm: Let's define $l_0=0$ and $r_{n+m+1}=n+m+1$. And $x_0=-2*10^9$, $x_{n+m+1} = 2*10^{9}$. In order to find $l_i$ for each $i$ we should iterate through the citizens from $1$ to $n+m$. If the $i$-th citizen is a taxi driver, then he/she is obviously the nearest taxi driver to himself/herself. If the $i$-th citizen is a rider, then $l_i=l_{i-1}$ In order to find $r_i$ for each $i$ we should iterate through the citizens from $n+m$ to $1$. If the $i$-th citizen is a taxi driver, then $r_i=i$, else $r_i=r_{i+1}$. Now it's time to compute the answer. Let's denote $b_i$ as the number of citizens, whose calls the $i$-th citizen will get (if the $i$-th citizen is a rider, then $b_i=0$). In order to do compute the values of array $b$ we should iterate through the citizens from $1$ to $n+m$. If the $i$-th citizen is a rider, then if the $x_{r_i}-x_i<x_i-x_{l_i}$ (distance between the nearest taxi driver at right and the $i$-th citizen is smaller than distance between the nearest taxi driver at the left and the citizen), then taxi driver $r_i$ will get the call, otherwise the taxi driver $l_i$ will get the call. So if $x_{r_i}-x_i<x_i-x_{l_i}$, then $b_{r_i}:=b_{r_i}+1$, else $b_{l_i}:=b_{l_i}+1$. In order to print out the answer we iterate through the citizens from $1$ to $n+m$. If the $i$-th citizen is a taxi driver, than we should print $b_i$. The algorithm iterates through the array four times, so overall complexity is $O(n+m)$
|
[
"implementation",
"sortings"
] | 1,200
| null |
1076
|
A
|
Minimizing the String
|
You are given a string $s$ consisting of $n$ lowercase Latin letters.
You have to remove \textbf{at most one} (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.
String $s = s_1 s_2 \dots s_n$ is lexicographically smaller than string $t = t_1 t_2 \dots t_m$ if $n < m$ and $s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$ or there exists a number $p$ such that $p \le min(n, m)$ and $s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$ and $s_p < t_p$.
For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".
|
By the definition of lexicographical comparing we can see that if we can remove one character we always have to do it. Besides, we have to remove the character from the leftmost position $i$ such that $i < n$ and $s_i > s_{i + 1}$ or from the position $n$ if there is no such $i$.
|
[
"greedy",
"strings"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
string s;
cin >> n >> s;
int pos = n - 1;
for (int i = 0; i < n - 1; ++i) {
if (s[i] > s[i + 1]) {
pos = i;
break;
}
}
cout << s.substr(0, pos) + s.substr(pos + 1) << endl;
return 0;
}
|
1076
|
B
|
Divisor Subtraction
|
You are given an integer number $n$. The following algorithm is applied to it:
- if $n = 0$, then end algorithm;
- find the smallest \textbf{prime} divisor $d$ of $n$;
- subtract $d$ from $n$ and go to step $1$.
Determine the number of subtrations the algorithm will make.
|
Notice that once the number becomes even, it never stops being even as subtracting $2$ doesn't change parity. Thus, the task is to find the smallest divisor, subtract it and print $1 + \frac{n - d}{2}$. Overall complexity: $O(\sqrt{n})$.
|
[
"implementation",
"math",
"number theory"
] | 1,200
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
long long get(long long n){
for (long long i = 2; i * i <= n; ++i)
if (n % i == 0)
return i;
return n;
}
int main() {
long long n;
scanf("%lld", &n);
long long cnt = 0;
if (n % 2 != 0){
n -= get(n);
++cnt;
}
printf("%lld\n", cnt + n / 2);
return 0;
}
|
1076
|
C
|
Meme Problem
|
Try guessing the statement from this picture:
You are given a non-negative integer $d$. You have to find two non-negative real numbers $a$ and $b$ such that $a + b = d$ and $a \cdot b = d$.
|
To solve this problem we need to use some math and solve the equation on the paper. If $a + b = d$ then $a = d - b$ and $a \cdot b = d$ transforms to $b (d - b) = d$ or $db - b^2 - d = 0$. Then $a, b = (d \pm \sqrt{D}) / 2$ where $D = d^2 - 4d$. So if $d = 0$ then $a = b = 0$, or if $0 < d < 4$ there is no answer. Since values are small, calculating answer in double was enough, all we need to do is just output answer with sufficient number of digits after the decimal point.
|
[
"binary search",
"math"
] | 1,300
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
typedef long long li;
typedef double ld;
typedef pair<int, int> pt;
li d;
inline bool read() {
if(!(cin >> d))
return false;
return true;
}
inline void solve() {
if(d == 0) {
cout << "Y " << 0.0 << " " << 0.0 << endl;
return;
}
if(d < 4) {
cout << "N" << endl;
return;
}
ld D = sqrt(d * li(d - 4));
ld a = (d + D) / 2.0;
ld b = (d - D) / 2.0;
cout << "Y " << a << " " << b << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
cout << fixed << setprecision(9);
int tc = 1;
assert(cin >> tc);
while(tc--) {
assert(read());
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1076
|
D
|
Edge Deletion
|
You are given an undirected connected weighted graph consisting of $n$ vertices and $m$ edges. Let's denote the length of the shortest path from vertex $1$ to vertex $i$ as $d_i$.
You have to erase some edges of the graph so that at most $k$ edges remain. Let's call a vertex $i$ \textbf{good} if there still exists a path from $1$ to $i$ with length $d_i$ after erasing the edges.
Your goal is to erase the edges in such a way that the number of \textbf{good} vertices is maximized.
|
Let's understand how many good vertices we may get if only $k$ edges remain. This value is not greater than $k + 1$, since an edge an add only one good vertex, and for $k = 0$ we have a good vertex with index $1$. This is an upper bound; let's try to find a solution getting exactly $k + 1$ good vertices (or, if $k + 1> n$, all vertices of the graph will be good). Let's run Dijkstra's algorithm from vertex $1$ and stop it as soon as we know the shortest paths to $k + 1$ vertices (including vertex $1$). The answer should contain the edges belonging to the shortest path tree built on these $k + 1$ vertices.
|
[
"graphs",
"greedy",
"shortest paths"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
vector<pair<int, pair<int, int> > > g[300043];
int main()
{
int n, m, k;
scanf("%d %d %d", &n, &m, &k);
for(int i = 0; i < m; i++)
{
int x, y, w;
scanf("%d %d %d", &x, &y, &w);
--x;
--y;
g[x].push_back(make_pair(y, make_pair(w, i)));
g[y].push_back(make_pair(x, make_pair(w, i)));
}
set<pair<long long, int> > q;
vector<long long> d(n, (long long)(1e18));
d[0] = 0;
q.insert(make_pair(0, 0));
vector<int> last(n, -1);
int cnt = 0;
vector<int> ans;
while(!q.empty() && cnt < k)
{
auto z = *q.begin();
q.erase(q.begin());
int k = z.second;
if(last[k] != -1)
{
cnt++;
ans.push_back(last[k]);
}
for(auto y : g[k])
{
int to = y.first;
int w = y.second.first;
int idx = y.second.second;
if(d[to] > d[k] + w)
{
q.erase(make_pair(d[to], to));
d[to] = d[k] + w;
last[to] = idx;
q.insert(make_pair(d[to], to));
}
}
}
printf("%d\n", ans.size());
for(auto x : ans) printf("%d ", x + 1);
}
|
1076
|
E
|
Vasya and a Tree
|
Vasya has a tree consisting of $n$ vertices with root in vertex $1$. At first all vertices has $0$ written on it.
Let $d(i, j)$ be the distance between vertices $i$ and $j$, i.e. number of edges in the shortest path from $i$ to $j$. Also, let's denote $k$-subtree of vertex $x$ — set of vertices $y$ such that next two conditions are met:
- $x$ is the ancestor of $y$ (each vertex is the ancestor of itself);
- $d(x, y) \le k$.
Vasya needs you to process $m$ queries. The $i$-th query is a triple $v_i$, $d_i$ and $x_i$. For each query Vasya adds value $x_i$ to each vertex from $d_i$-subtree of $v_i$.
Report to Vasya all values, written on vertices of the tree after processing all queries.
|
To solve this problem we can use a data structure which allows to add some value on segment and get a value from some point (Fenwick tree, segment tree or anything you are familliar with). Let's run DFS from the root while maintaining current depth. When entering a vertex $u$ on depth $h$, let's consider all queries having $v_i = u$, and for each such query add $x_i$ on segment $[h, h + d_i]$. Then for current vertex $u$ the answer is the value in point $h$. When leaving vertex $u$ we need to rollback everything we have done: for all queries having $v_i = u$ subtract $x_i$ on segment $[h, h + d_i]$.
|
[
"data structures",
"trees"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 9;
int n, m;
vector <int> g[N];
vector <pair<int, int> > q[N];
long long add[N];
long long res[N];
void dfs(int v, int pr, int h, long long sum){
for(auto p : q[v]){
int l = h, r = h + p.first;
add[l] += p.second;
if(r + 1 < N) add[r + 1] -= p.second;
}
sum += add[h];
res[v] = sum;
for(auto to : g[v])
if(to != pr)
dfs(to, v, h + 1, sum);
for(auto p : q[v]){
int l = h, r = h + p.first;
add[l] -= p.second;
if(r + 1 < N) add[r + 1] += p.second;
}
}
int main() {
// freopen("input.txt", "r", stdin);
scanf("%d", &n);
for(int i = 0; i < n - 1; ++i){
int u, v;
scanf("%d %d", &u, &v);
--u, --v;
g[u].push_back(v);
g[v].push_back(u);
}
scanf("%d", &m);
for(int i = 0; i < m; ++i){
int v, h, d;
scanf("%d %d %d", &v, &h, &d);
--v;
q[v].push_back(make_pair(h, d));
}
dfs(0, 0, 0, 0);
for(int i = 0; i < n; ++i)
printf("%lld ", res[i]);
puts("");
return 0;
}
|
1076
|
F
|
Summer Practice Report
|
Vova has taken his summer practice this year and now he should write a report on how it went.
Vova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exactly $n$ pages and the $i$-th page will include $x_i$ tables and $y_i$ formulas. The pages are numbered from $1$ to $n$.
Vova fills the pages one after another, he can't go filling page $i + 1$ before finishing page $i$ and he can't skip pages.
However, if he draws \textbf{strictly more} than $k$ tables in a row or writes \textbf{strictly more} than $k$ formulas in a row then he will get bored. Vova wants to rearrange tables and formulas in each page in such a way that he doesn't get bored in the process. Vova can't move some table or some formula to another page.
Note that the count doesn't reset on the start of the new page. For example, if the page ends with $3$ tables and the next page starts with $5$ tables, then it's counted as $8$ tables in a row.
Help Vova to determine if he can rearrange tables and formulas on each page in such a way that there is no more than $k$ tables in a row and no more than $k$ formulas in a row.
|
Let's intruduce the following dynamic programming approach. $dp[N][2]$, $dp[i][j]$ is the smallest number of elements of type $j$ page $i$ can end with. If we learn to recalculate it, the answer will be "YES" if $dp[n][0] \le k$ or $dp[n][1] \le k$. I will try to prove it on the fly. Let's look into the constructing of each page from the following perspective. I'll consider the cases when the current page ends with tables and the previous page ends with either tables or formulas. Let's write down all the tables and then put formulas as separators to them. I will call number of tables on the end of the previous page $pa$, the number of formulas on the end of the previous page $pb$, the number on tables on the current page $a$ and the number of formulas on the current page $b$. In the case with tables on the end of the previous page the smallest number of separators you can have is $cnt = \lceil \frac{pa + a}{k} \rceil - 1$. Moreover, if you have $b > cnt$, you can put one of the formulas right before the end of the page, ending it with $1$ table. The only case is when there are too many separators. $b$ should be less or equal to $a \cdot k$ (you can put up to $k$ separators before each table). The case with formulas on the end of the previous page isn't that different. The smallest number of separators is $cnt = \lceil \frac{a}{k} \rceil - 1$ and the limit to the number of separators is $(a - 1) \cdot k + (k - pb)$ (you can't put $k$ separators before the first table as in the first case, the maximum number to that position is determined by the previous page). Now let's take a look at resulting expressions. You can notice that lowering $pa$ can only decrease the lower bound on the number of separators and lowering $pb$ can only increase the upper bound on the number of separators. That shows that minimizing the values in $dp[i][j]$ is always profitable. Overall complexity: $O(n)$.
|
[
"dp",
"greedy"
] | 2,500
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
typedef long long li;
const int N = 300 * 1000 + 13;
const int INF = 1e9;
int dp[N][2];
int n, k;
int a[N], b[N];
int get(int pa, int pb, int a, int b){
int ans = INF;
if (pa <= k){
int tot = pa + a;
int cnt = (tot + k - 1) / k - 1;
if (b == cnt)
ans = min(ans, tot - cnt * k);
else if (b > cnt && b <= a * li(k))
ans = min(ans, 1);
}
if (pb <= k){
int cnt = (a + k - 1) / k - 1;
if (b == cnt)
ans = min(ans, a - cnt * k);
else if (b > cnt && b <= (a - 1) * li(k) + (k - pb))
ans = min(ans, 1);
}
return ans;
}
int main() {
scanf("%d%d", &n, &k);
forn(i, n) scanf("%d", &a[i]);
forn(i, n) scanf("%d", &b[i]);
forn(i, N) forn(j, 2) dp[i][j] = INF;
dp[0][0] = 0;
dp[0][1] = 0;
forn(i, n){
dp[i + 1][0] = get(dp[i][0], dp[i][1], a[i], b[i]);
dp[i + 1][1] = get(dp[i][1], dp[i][0], b[i], a[i]);
}
puts(dp[n][0] <= k || dp[n][1] <= k ? "YES" : "NO");
return 0;
}
|
1076
|
G
|
Array Game
|
Consider a following game between two players:
There is an array $b_1$, $b_2$, ..., $b_k$, consisting of positive integers. Initially a chip is placed into the first cell of the array, and $b_1$ is decreased by $1$. Players move in turns. Each turn the current player has to do the following: if the index of the cell where the chip is currently placed is $x$, then he or she has to choose an index $y \in [x, min(k, x + m)]$ such that $b_y > 0$, move the chip to the cell $y$ and decrease $b_y$ by $1$. If it's impossible to make a valid move, the current player loses the game.
Your task is the following: you are given an array $a$ consisting of $n$ positive integers, and $q$ queries to it. There are two types of queries:
- $1$ $l$ $r$ $d$ — for every $i \in [l, r]$ increase $a_i$ by $d$;
- $2$ $l$ $r$ — tell who is the winner of the game that is played on the subarray of $a$ from index $l$ to index $r$ inclusive. Assume both players choose an optimal strategy.
|
Suppose there is only one query, i. e. we are given some array and we want to know who is the winner if the game is played on this array. One of the obvious solutions is $dp[i][x]$ - will the current player win if the chip is currently in the cell $i$ and the number in cell $i$ is $x$. We can already see that we don't need to know the exact value of $x$, we only want to know whether it's odd: if there is a cell $j \ne i$ such that we can go from $i$ to $j$ and $dp[j][a_j - 1]$ is a state where current player will lose, then we should go to this cell since our opponent will enter a losing state of the game. Otherwise, we want to force our opponent to move out of cell $i$, and we can do so only if $x$ is odd. So we found a dynamic programming solution with $O(n)$ states, but what is more important is that we can take all the elements in our array modulo $2$. Okay, now let's solve the problem when there are only queries of type $2$ (no modifications). Since when calculating the $dp$ values we are interested only in $m$ next cells, and there are only $2^m$ variants of whether these cells are "winning" or "losing", we may consider each element of the array as a function that maps a mask of $m$ next states into a new mask of $m$ states if we pushed our new element into the front. For example, if the $i$-th element is even and states $i + 1$, $i + 2$, $i + 3$, $i + 4$, $i + 5$ are winning, losing, losing, winning and losing respectively, and $m = 5$, then we may consider a mask of next states as $10010$; and then we can check if $i$-th state is winning and push a bit to the front of this mask, discarding the last bit; since new state is winning, we will get a mask of $11001$. It allows us to denote two functions $f_0(x)$ and $f_1(x)$ - what will be the resulting mask of next $m$ states, if current mask is $x$ and we push an even or odd element to the front. Okay, what about pushing more than one element? We can just take the composition of their functions! Since a function can be stored as an array of $2^m$ integers and the composition needs only $O(2^m)$ time to be calculated, then we can build a segment tree over the elements of the array, and store a composition of all functions on the segment in each node. This allows us to answer queries of type $2$ in $O(2^m \log n)$. The only thing that's left is additions on segment. Adding an even number is easy: just ignore this query. To be able an odd number, let's store another function in each node of the segment tree which would be the composition of all functions on the segment if we would add $1$ to all elements on the segment (so the elements which were odd become even, and vice versa). This allows us to use lazy propagation: if the query affects the whole node, we may just swap two functions in it and push the query to the children of this node. Overall complexity is $O(2^m (n + q) \log n)$. It turns out (we didn't think about it before the contest, but some contestants submitted such solutions) that it can be reduced to $O(m (n + q) \log n)$ if we will use the distance to closest losing state instead of a mask of winning and losing states.
|
[
"data structures",
"games"
] | 3,000
|
#include <bits/stdc++.h>
using namespace std;
const int N = 200043;
typedef long long li;
int n, m;
li a[N];
int q;
int f[N * 4];
vector<int> T[4 * N];
vector<int> T2[4 * N];
int mask;
int cur;
vector<int> combine(const vector<int>& a, const vector<int>& b)
{
vector<int> c(1 << m);
for(int i = 0; i < (1 << m); i++)
c[i] = b[a[i]];
return c;
}
vector<int> init(li x)
{
vector<int> ans(1 << m);
for(int i = 0; i < (1 << m); i++)
{
if(i != mask || (x & 1) == 0)
ans[i] = ((i << 1) & mask) ^ 1;
else
ans[i] = ((i << 1) & mask);
}
return ans;
}
void upd(int v)
{
T[v] = combine(T[v * 2 + 2], T[v * 2 + 1]);
T2[v] = combine(T2[v * 2 + 2], T2[v * 2 + 1]);
}
void build(int v, int l, int r)
{
if(l == r - 1)
{
T[v] = init(a[l]);
T2[v] = init(a[l] ^ 1);
return;
}
int m = (l + r) >> 1;
build(v * 2 + 1, l, m);
build(v * 2 + 2, m, r);
upd(v);
}
void push(int v, int l, int r)
{
if(f[v])
{
swap(T[v], T2[v]);
if(l != r - 1)
{
f[v * 2 + 1] ^= 1;
f[v * 2 + 2] ^= 1;
}
f[v] = 0;
}
}
vector<int> id;
void get(int v, int l, int r, int L, int R)
{
push(v, l, r);
if(L >= R)
return;
if(l == L && r == R)
{
cur = T[v][cur];
}
else
{
int m = (l + r) >> 1;
get(v * 2 + 2, m, r, max(L, m), R);
get(v * 2 + 1, l, m, L, min(R, m));
upd(v);
}
}
void add(int v, int l, int r, int L, int R)
{
push(v, l, r);
if(L >= R)
return;
if(l == L && r == R)
{
f[v] ^= 1;
push(v, l, r);
return;
}
else
{
int m = (l + r) >> 1;
add(v * 2 + 1, l, m, L, min(R, m));
add(v * 2 + 2, m, r, max(L, m), R);
upd(v);
}
}
int main()
{
scanf("%d %d %d", &n, &m, &q);
mask = (1 << m) - 1;
for(int i = 0; i < (1 << m); i++)
id.push_back(i);
for(int i = 0; i < n; i++)
scanf("%lld", &a[i]);
build(0, 0, n);
for(int i = 0; i < q; i++)
{
int t, l, r;
scanf("%d %d %d", &t, &l, &r);
--l;
if(t == 1)
{
li d;
scanf("%lld", &d);
if(d & 1)
add(0, 0, n, l, r);
}
else
{
cur = mask;
get(0, 0, n, l, r);
if((cur & 1) == 1)
puts("1");
else
puts("2");
}
}
}
|
1077
|
A
|
Frog Jumping
|
A frog is currently at the point $0$ on a coordinate axis $Ox$. It jumps by the following algorithm: the first jump is $a$ units to the right, the second jump is $b$ units to the left, the third jump is $a$ units to the right, the fourth jump is $b$ units to the left, and so on.
Formally:
- if the frog has jumped an even number of times (before the current jump), it jumps from its current position $x$ to position $x+a$;
- otherwise it jumps from its current position $x$ to position $x-b$.
Your task is to calculate the position of the frog after $k$ jumps.
But... One more thing. You are watching $t$ different frogs so you have to answer $t$ independent queries.
|
With each pair of jumps of kind "to the right - to the left" the frog jumps $a - b$. So the answer is almost $(a - b) \cdot \lfloor\frac{k}{2}\rfloor$. Almost because there can be one more jump to the right. So if $k$ is odd then we have to add $a$ to the answer.
|
[
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
int a, b, k;
cin >> a >> b >> k;
cout << (a - b) * 1ll * (k / 2) + a * (k & 1) << endl;
}
return 0;
}
|
1077
|
B
|
Disturbed People
|
There is a house with $n$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $n$ integer numbers $a_1, a_2, \dots, a_n$, where $a_i = 1$ if in the $i$-th flat the light is on and $a_i = 0$ otherwise.
Vova thinks that people in the $i$-th flats are disturbed and cannot sleep if and only if $1 < i < n$ and $a_{i - 1} = a_{i + 1} = 1$ and $a_i = 0$.
Vova is concerned by the following question: what is the minimum number $k$ such that if people from exactly $k$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $k$.
|
The first observation is that we are interested only in patterns of kind "101". All other patterns don't make sense at all. So, let's build a greedy approach. Let's iterate over the given array from the left to the right and maintain that the prefix of the given answer is already correct. If now we are at some position $i$, $a_{i - 1} = a_{i + 1} = 1$ and $a_i = 0$ (and the prefix from $1$ to $i-2$ is already correct) then which one $1$ we have to replace? When we replace the left one then we cannot do better in the future, but when we replace the right one then we can fix some on the suffix of the array. The easiest example is "1101011". If now we are at the position $3$ then we will do better if we will set $a_4 := 0$.
|
[
"greedy"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int ans = 0;
for (int i = 1; i < n - 1; ++i) {
if (a[i] == 0 && a[i - 1] == 1 && a[i + 1] == 1) {
++ans;
a[i + 1] = 0;
}
}
cout << ans << endl;
return 0;
}
|
1077
|
C
|
Good Array
|
Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $a=[1, 3, 3, 7]$ is good because there is the element $a_4=7$ which equals to the sum $1 + 3 + 3$.
You are given an array $a$ consisting of $n$ integers. Your task is to print all indices $j$ of this array such that after removing the $j$-th element from the array it will be good (let's call such indices nice).
For example, if $a=[8, 3, 5, 2]$, the nice indices are $1$ and $4$:
- if you remove $a_1$, the array will look like $[3, 5, 2]$ and it is good;
- if you remove $a_4$, the array will look like $[8, 3, 5]$ and it is good.
You have to consider all removals \textbf{independently}, i. e. remove the element, check if the resulting array is good, and return the element into the array.
|
The first part: calculate the sum of the whole array: $sum = \sum\limits_{i = 1}^n a_i$ (be careful, it can be $2 \cdot 10^{11}$!). The second part: let's maintain an array $cnt$ of size $10^6 + 1$ where $cnt_i$ will be equal to the number of elements in the given array equals to $i$. The third part: iterate over the array, let the current position be $i$. Set $sum := sum - a_i$, make $cnt_{a_i} := cnt_{a_i} - 1$. If $sum$ is even, $\frac{sum}{2} \le 10^6$ and $cnt_{\frac{sum}{2}} > 0$ then the index $i$ is nice otherwise it doesn't. And after all make $cnt_{a_i} := cnt_{a_i} + 1$ and set $sum := sum + a_i$.
|
[] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e6;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
vector<int> cnt(MAX + 1);
for (int i = 0; i < n; ++i) {
cin >> a[i];
++cnt[a[i]];
}
long long sum = accumulate(a.begin(), a.end(), 0ll);
vector<int> ans;
for (int i = 0; i < n; ++i) {
sum -= a[i];
--cnt[a[i]];
if (sum % 2 == 0 && sum / 2 <= MAX && cnt[sum / 2] > 0) {
ans.push_back(i);
}
sum += a[i];
++cnt[a[i]];
}
cout << ans.size() << endl;
for (auto it : ans) cout << it + 1 << " ";
cout << endl;
return 0;
}
|
1077
|
D
|
Cutting Out
|
You are given an array $s$ consisting of $n$ integers.
You have to find \textbf{any} array $t$ of length $k$ such that you can cut out maximum number of copies of array $t$ from array $s$.
Cutting out the copy of $t$ means that for each element $t_i$ of array $t$ you have to find $t_i$ in $s$ and remove it from $s$. If for some $t_i$ you cannot find such element in $s$, then you cannot cut out one more copy of $t$. The both arrays can contain duplicate elements.
For example, if $s = [1, 2, 3, 2, 4, 3, 1]$ and $k = 3$ then one of the possible answers is $t = [1, 2, 3]$. This array $t$ can be cut out $2$ times.
- To cut out the first copy of $t$ you can use the elements $[1, \underline{\textbf{2}}, 3, 2, 4, \underline{\textbf{3}}, \underline{\textbf{1}}]$ (use the highlighted elements). After cutting out the first copy of $t$ the array $s$ can look like $[1, 3, 2, 4]$.
- To cut out the second copy of $t$ you can use the elements $[\underline{\textbf{1}}, \underline{\textbf{3}}, \underline{\textbf{2}}, 4]$. After cutting out the second copy of $t$ the array $s$ will be $[4]$.
Your task is to find such array $t$ that you can cut out the copy of $t$ from $s$ maximum number of times. If there are multiple answers, you may choose \textbf{any} of them.
|
Let's solve the problem using binary search by the answer. It is easy to see that if we can construct the answer for some number of copies $val$ then we also can do it for $val - 1$. The only thing we need is to write the function $can(val)$ which will say can we cut off $val$ copies of some array $t$ from $s$ or not. Let's imagine $val$ copies of string $t$ as a matrix of size $val \times k$. Obviously, each row of this matrix should be equal to each other row. Let's fill not rows but columns of this matrix. For some element $i$ of $s$ we can easy notice that we can take exactly $\lfloor\frac{cnt_i}{val}\rfloor$ columns containing this element where $cnt_i$ is the number of such elements in $s$. So, overall number of columns we can fill in this matrix will be $\sum\limits_{i = 1}^{2 \cdot 10^5} \lfloor\frac{cnt_i}{val}\rfloor$. If this value is greater than or equal to $k$ then $can(val)$ is true otherwise it is false. It is easy to construct the answer using all things we described above. Overall complexity is $O(n + |A|\log n)$ where $|A|$ is the size of the alphabet.
|
[
"binary search",
"sortings"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200 * 1000 + 1;
int n, k;
vector<int> s, t;
vector<int> cnts(MAX);
bool can(int cnt) {
t.clear();
for (int i = 0; i < MAX; ++i) {
int need = min(cnts[i] / cnt, k - int(t.size()));
for (int j = 0; j < need; ++j) {
t.push_back(i);
}
}
return int(t.size()) == k;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n >> k;
s = vector<int>(n);
for (int i = 0; i < n; ++i) {
cin >> s[i];
}
for (auto c : s) {
++cnts[c];
}
int l = 0, r = n;
while (r - l > 1) {
int mid = (l + r) >> 1;
if (can(mid)) {
l = mid;
} else {
r = mid;
}
}
if (!can(r)) can(l);
for (auto it : t) cout << it << " ";
cout << endl;
return 0;
}
|
1077
|
E
|
Thematic Contests
|
Polycarp has prepared $n$ competitive programming problems. The topic of the $i$-th problem is $a_i$, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and \textbf{all contests should have pairwise distinct topics}. He may not use all the problems. It is possible that there are no contests for some topics.
Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:
- number of problems in each contest is \textbf{exactly twice} as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
- the total number of problems in all the contests should be maximized.
Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.
|
The first thing: we don't need the problems, we need their counts. So let's calculate for each topic the number of problems with this topic and sort them in non-decreasing order. The counting can be done with std::map or another one sorting. The second thing: the answer is not exceed $n$ (very obviously). So let's iterate over the number of problems in maximum by the number of problems thematic contest. Now we have to calculate the maximum number of problems we can take in the set of thematic contests. Let's do it greedily. The number of contests in the set don't exceed $\log n$. Let the number of problems in the current contest be $cur$ (at the beginning of iteration the current contest is the maximum by the number of problems). Let's take the topic with the maximum number of problems for this contest. If we cannot do it, stop the iteration. Otherwise we can (maybe) continue the iteration. If $cur$ is even then divide it by $2$ and continue with the rest of topics, otherwise stop the iteration. Which topic we have to choose for the second one contest? The answer is: the topic with the maximum number of problems (which isn't chosen already). So let's carry the pointer $pos$ (initially it is at the end of the array of counts) and decrease it when we add another one contest to our set. All calculations inside the iteration are very obviously. Let's notice that one iteration spends at most $\log n$ operations. So overall complexity of the solution is $O(n \log n)$. The last question is: why can we take the maximum by the number of problems topic each time? Suppose we have two contests with numbers of problems $x$ and $y$, correspondingly. Let's consider the case when $x < y$. Let the number of problems of the first contest topic be $cnt_x$ and the number of problems of the second contest topic be $cnt_y$. The case $cnt_x \le cnt_y$ don't break our assumptions. The only case which can break our assumptions is $cnt_x > cnt_y$. So if it is then we can swap these topics (because $x < y$ and $cnt_x > cnt_y$) and all will be okay. So this greedy approach works.
|
[
"greedy",
"sortings"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
map<int, int> cnt;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
++cnt[x];
}
vector<int> cnts;
for (auto it : cnt) {
cnts.push_back(it.second);
}
sort(cnts.begin(), cnts.end());
int ans = 0;
for (int i = 1; i <= cnts.back(); ++i) {
int pos = int(cnts.size()) - 1;
int cur = i;
int res = cur;
while (cur % 2 == 0 && pos > 0) {
cur /= 2;
--pos;
if (cnts[pos] < cur) break;
res += cur;
}
ans = max(ans, res);
}
cout << ans << endl;
return 0;
}
|
1077
|
F1
|
Pictures with Kittens (easy version)
|
\textbf{The only difference between easy and hard versions is the constraints.}
Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $i$-th picture has beauty $a_i$.
Vova wants to repost exactly $x$ pictures in such a way that:
- each segment of the news feed of at least $k$ consecutive pictures has at least one picture reposted by Vova;
- the sum of beauty values of reposted pictures is maximum possible.
For example, if $k=1$ then Vova has to repost all the pictures in the news feed. If $k=2$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.
Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
|
Let's solve the problem using dynamic programming. Let $dp_{i, j}$ be the maximum total beauty of pictures if Vova is at the $i$-th picture now, the number of remaining reposts is $j$ and Vova reposted the $i$-th picture. Initially, $dp_{0, x} = 0$ and all other values of $dp$ are $-\infty$. Let's learn to do some transitions to calculate this dynamic programming. What is the way to do it? Let's iterate over the position of the previously reposted picture and try to update $dp_{i, j}$ using previously calculated values. Obviously, this position can be from $i-1$ to $i-k$. So let's iterate over the position (let it be $p$) and if $dp_{p, j + 1}$ (we need one more repost to repost the $i$-th picture) is not $-\infty$ then try to update $dp_{i, j} = max(dp_{i, j}, dp_{p, j + 1} + a_i$) (pictures are $1$-indexed). So, where can we find the answer? The answer is $\max\limits_{i = n - k + 1}^{n} dp_{i}$. If this value is $-\infty$ then the answer is -1. Overall complexity is $O(nkx)$.
|
[
"dp"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
const long long INF64 = 1e18;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k, x;
cin >> n >> k >> x;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
vector<vector<long long>> dp(n + 1, vector<long long>(x + 1, -INF64));
dp[0][x] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < x; ++j) {
for (int p = 1; p <= k; ++p) {
if (i - p < 0) break;
if (dp[i - p][j + 1] == -INF64) {
continue;
}
dp[i][j] = max(dp[i][j], dp[i - p][j + 1] + a[i - 1]);
}
}
}
long long ans = -INF64;
for (int i = n - k + 1; i <= n; ++i) {
ans = max(ans, *max_element(dp[i].begin(), dp[i].end()));
}
if (ans == -INF64) ans = -1;
cout << ans << endl;
return 0;
}
|
1077
|
F2
|
Pictures with Kittens (hard version)
|
\textbf{The only difference between easy and hard versions is the constraints.}
Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $i$-th picture has beauty $a_i$.
Vova wants to repost exactly $x$ pictures in such a way that:
- each segment of the news feed of at least $k$ consecutive pictures has at least one picture reposted by Vova;
- the sum of beauty values of reposted pictures is maximum possible.
For example, if $k=1$ then Vova has to repost all the pictures in the news feed. If $k=2$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.
Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
|
Let's use dynamic programming described in the previous tutorial to solve this problem too. But its complexity is $O(nkx)$ so we have to improve some part of the solution. Let's see how we do transitions in this dp: for $p \in [i-k; i-1]$ $dp_{i, j} = max(dp_{i, j}, dp_{p, j + 1} + a_i)$. What can we do to optimize it? $a_i$ is the constant and we have to take the maximum value among $dp_{i - k, j + 1}, dp_{i - k + 1, j + 1}, \dots, dp_{i - 1, j + 1}$. You will say "segment tree"! I say no. Not a segment tree. Not a sparse table. Not a cartesian tree or some other logarithmic data structures. If you want to spend a lot of time to fit such solution in time and memory limits - okay, it is your choice. I prefer the queue with supporting the maximum on it. The last part of this tutorial will be a small guide about how to write and use the queue with supporting the maximum on it. The first part of understanding this data structure is the stack with the maximum. How do we support the stack with the maximum on it? That's pretty easy: let's maintain the stack of pairs, when the first value of pair is the value in the stack and the second one is the maximum on the stack if this element will be the topmost. Then when we push some value $val$ in it, the first element of pair will be $val$ and the second one will be $max(val, s.top().second)$ (if $s$ is our stack and $top()$ is the topmost element). When we pop the element we don't need any special hacks to do it. Just pop it. And the maximum on the stack is always $s.top().second$. Okay, the second part of understanding this data structure is the queue on two stacks. Let's maintain two stacks $s1$ and $s2$ and try to implement the queue using it. We will push elements only to $s2$ and pop elements only from $s1$. Then how to maintain the queue using such stacks? The push is pretty easy - just push it in $s2$. The main problem is pop. If $s1$ is not empty then we have to pop it from $s1$. But what do we do if $s1$ is empty? No problems: let's just transfer elements of $s2$ to $s1$ (pop from $s2$, push to $s1$) in order from top to bottom. And don't forget to pop the element after this transfer! Okay, if we will join these two data structures, we can see that we obtain exactly what we want! Just two stacks with maximums! That's pretty easy to understand and implement it. The last part of the initial solution is pretty easy - just apply this data structure (in fact, $x+1$ data structures) to do transitions in our dynamic programming. The implementation of this structure can be found in the authors solution. Total complexity of the solution is $O(nx)$.
|
[
"data structures",
"dp"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp make_pair
typedef long long li;
typedef pair<li, li> pll;
const li INF64 = 1e18;
struct myQueue {
stack<pll> s1, s2;
int size() {
return s1.size() + s2.size();
}
bool isEmpty() {
return size() == 0;
}
long long getMax() {
if (isEmpty()) {
return -INF64;
}
if (!s1.empty() && !s2.empty()) {
return max(s1.top().y, s2.top().y);
}
if (!s1.empty()) {
return s1.top().y;
}
return s2.top().y;
}
void push(long long val) {
if (s2.empty()) {
s2.push(mp(val, val));
} else {
s2.push(mp(val, max(val, s2.top().y)));
}
}
void pop() {
if (s1.empty()) {
while (!s2.empty()) {
if (s1.empty()) {
s1.push(mp(s2.top().x, s2.top().x));
} else {
s1.push(mp(s2.top().x, max(s2.top().x, s1.top().y)));
}
s2.pop();
}
}
assert(!s1.empty());
s1.pop();
}
};
int n, k, x;
vector<int> a;
vector<myQueue> q;
vector<queue<int>> pos;
vector<vector<long long>> dp;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n >> k >> x;
a = vector<int>(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
q = vector<myQueue>(x + 1);
pos = vector<queue<int>>(x + 1);
dp = vector<vector<long long>>(n + 1, vector<long long>(x + 1, -INF64));
dp[0][x] = 0;
pos[x].push(-1);
q[x].push(0ll);
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= x; ++j) {
while (!pos[j].empty() && pos[j].front() < i - k - 1) {
q[j].pop();
pos[j].pop();
}
}
for (int j = 0; j < x; ++j) {
if (!q[j + 1].isEmpty()) {
dp[i][j] = max(dp[i][j], q[j + 1].getMax() + a[i - 1]);
q[j].push(dp[i][j]);
pos[j].push(i - 1);
}
}
}
long long ans = -INF64;
for (int i = n - k + 1; i <= n; ++i) {
ans = max(ans, *max_element(dp[i].begin(), dp[i].end()));
}
if (ans == -INF64) ans = -1;
cout << ans << endl;
return 0;
}
|
1078
|
E
|
Negative Time Summation
|
Everyone knows that computers become faster and faster. Recently Berland scientists have built a machine that can move itself back in time!
More specifically, it works as follows. It has an infinite grid and a robot which stands on one of the cells. Each cell of the grid can either be empty or contain 0 or 1. The machine also has a program which consists of instructions, which are being handled one by one. Each instruction is represented by exactly one symbol (letter or digit) and takes exactly one unit of time (say, second) to be performed, except the last type of operation (it's described below). Here they are:
- 0 or 1: the robot places this number into the cell he is currently at. If this cell wasn't empty before the operation, its previous number is replaced anyway.
- e: the robot \textbf{e}rases the number into the cell he is at.
- l, r, u or d: the robot goes one cell to the \textbf{l}eft/\textbf{r}ight/\textbf{u}p/\textbf{d}own.
- s: the robot \textbf{s}tays where he is for a unit of time.
- t: let $x$ be $0$, if the cell with the robot is empty, otherwise let $x$ be one more than the digit in this cell (that is, $x = 1$ if the digit in this cell is $0$, and $x = 2$ if the digit is $1$). Then the machine \textbf{t}ravels $x$ seconds back in time. Note that this doesn't change the instructions order, but it changes the position of the robot and the numbers in the grid as they were $x$ units of time ago. You can consider this instruction to be equivalent to a Ctrl-Z pressed $x$ times.
For example, let the board be completely empty, and the program be sr1t0. Let the robot initially be at $(0, 0)$.
- [now is the moment $0$, the command is s]: we do nothing.
- [now is the moment $1$, the command is r]: we are now at $(1, 0)$.
- [now is the moment $2$, the command is 1]: we are at $(1, 0)$, and this cell contains $1$.
- [now is the moment $3$, the command is t]: we travel $1 + 1 = 2$ moments back, that is, to the moment $1$.
- [now is the moment $1$, the command is 0]: we are again at $(0, 0)$, and the board is clear again, but after we follow this instruction, this cell has $0$ in it. We've just rewritten the history. The consequences of the third instruction have never happened.
Now Berland scientists want to use their machine in practice. For example, they want to be able to add two integers.
Assume that the initial state of the machine is as follows:
- One positive integer is written in binary on the grid in such a way that its right bit is at the cell $(0, 1)$, from left to right from the highest bit to the lowest bit.
- The other positive integer is written in binary on the grid in such a way that its right bit is at the cell $(0, 0)$, from left to right from the highest bit to the lowest bit.
- All the other cells are empty.
- The robot is at $(0, 0)$.
- We consider this state to be always in the past; that is, if you manage to travel to any negative moment, the board was always as described above, and the robot was at $(0, 0)$ for eternity.
You are asked to write a program after which
- The robot stands on a non-empty cell,
- If we read the number starting from the cell with the robot and moving to the right until the first empty cell, this will be $a + b$ in binary, from the highest bit to the lowest bit.
Note that there are no restrictions on other cells. In particular, there may be a digit just to the left to the robot after all instructions.
In each test you are given up to $1000$ pairs $(a, b)$, and your program must work for all these pairs. Also since the machine's memory is not very big, your program must consist of no more than $10^5$ instructions.
|
Disclaimer: there seem to be solutions much simpler than the author's. You can read some passed codes. Let's define our workplace as follows: we will take 6 rows, containing (in order from up to down): carry bits, bits of $a$, bits of $b$, two lines of some buffer garbage and the line with the answer. Consequently, these strings have $y$-coordinates from $2$ to $-3$. Now our plan is to do the following: add leading zeroes to the left of $a$ and $b$, go back to the right end of numbers, a little more than $30$ times (say, $32$) do the following: add a zero carry bit, if necessary, calculate $xor(carry, a_i, b_i)$, which is the $i$-th digit of the result, calculate $maj(carry, a_i, b_i)$, which is the new carry ($maj$ is the majority function which returns $1$ iff at least $2$ of $3$ arguments are $1$), move one cell to the left to the next digits. To do this we can implement some helper functions. Let inv(dir) be the direction opposite to dir (for example, inv(l) = r): move_if_1(dir) = <dir><inv(dir)>st This means that after running the subprogram, say, lrst, robot goes one cell to the left iff it was standing on $1$, otherwise it doesn't do anything. Let's write some other subprograms: move_if_0(dir) = <dir><inv(dir)>t move_if_not_empty(dir) = <dir>s<inv(dir)>t copy(dir) = <dir>10<inv(dir)>t The last subprogram copies a symbol one cell to the given direction. It's important that it's the first function which works properly only when the robot is standing on a non-empty cell. Explaining how to build a maj and xor of three arguments seems really hard to me, but the idea is as follows: we (ab)use the fact that these functions are symmetric (that is, their result doesn't depend on the order of the arguments), so if we have three bits one under another and we want to obtain some $f(x, y, z)$ somewhere under them, we can first copy them one, two and three times, respectively, place necessary bits in the buffer zone and then do something like move_if_1(r) d move_if_1(r) d move_if_1(r) d do_something In the end we should obtain something like this (if numbers were no more than two bits long): Here is a gif with our algorithm adding 2 to 3 if the length was no more than 2.
|
[
"constructive algorithms"
] | 3,400
| null |
1080
|
A
|
Petya and Origami
|
Petya is having a party soon, and he has decided to invite his $n$ friends.
He wants to make invitations in the form of origami. For each invitation, he needs \textbf{two} red sheets, \textbf{five} green sheets, and \textbf{eight} blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only \textbf{one} color with $k$ sheets. That is, each notebook contains $k$ sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all $n$ of his friends.
|
Let's calculate how many notebooks we need for each color separately, and the answer, obviously, will be their sum. We need $2 \cdot n$ red sheets, $5 \cdot n$ green sheets, and $8 \cdot n$ blue sheets. So we need $\lceil \frac {2n}{k} \rceil$ notebooks with red sheets, $\lceil \frac{5n}{k} \rceil$ and $\lceil \frac{8n}{k} \rceil$ notebooks with of green sheets and blue sheets, respectively.
|
[
"math"
] | 800
|
# include <iostream>
# include <cmath>
# include <algorithm>
# include <stdio.h>
# include <cstdint>
# include <cstring>
# include <string>
# include <cstdlib>
# include <vector>
# include <bitset>
# include <map>
# include <queue>
# include <ctime>
# include <stack>
# include <set>
# include <list>
# include <random>
# include <deque>
# include <functional>
# include <iomanip>
# include <sstream>
# include <fstream>
# include <complex>
# include <numeric>
# include <immintrin.h>
# include <cassert>
# include <array>
# include <tuple>
# include <unordered_set>
# include <unordered_map>
using namespace std;
int main(int argc, const char * argv[]) {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n,k;
int res,cur;
cin>>n>>k;
res=0;
cur=n*2;
res+=(cur+k-1)/k;
cur=n*5;
res+=(cur+k-1)/k;
cur=n*8;
res+=(cur+k-1)/k;
cout<<res<<endl;
}
|
1080
|
B
|
Margarite and the best present
|
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.
Recently, she was presented with an array $a$ of the size of $10^9$ elements that is filled as follows:
- $a_1 = -1$
- $a_2 = 2$
- $a_3 = -3$
- $a_4 = 4$
- $a_5 = -5$
- And so on ...
That is, the value of the $i$-th element of the array $a$ is calculated using the formula $a_i = i \cdot (-1)^i$.
She immediately came up with $q$ queries on this array. Each query is described with two numbers: $l$ and $r$. The answer to a query is the sum of all the elements of the array at positions from $l$ to $r$ inclusive.
Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.
Help her find the answers!
|
At first let's simplify the problem. Let's denote as $f(x)$ function that returns sum of the elements of the array that have indices from $1$ to $x$ inclusive. In order to calculate the function in a fast and easy way let's split the task into two parts: If $x$ is even, then the sum is equal to: $f(x) = -1 + 2 - 3 + 4 - \cdots - (x - 1) + x$ $f(x) = (-1 + 2) + (-3 + 4) + \cdots + (-(x - 1) + x)$ Since the number $x$ is even the number of such pairs is equal to $\frac{x}{2}$. Since the sum of the elements of each pair is equal to $1$, than $f(x) = \frac{x}{2}$ Since the number $x$ is even the number of such pairs is equal to $\frac{x}{2}$. Since the sum of the elements of each pair is equal to $1$, than If $x$ is odd, than the sum is equal to: $f(x) = -1 + 2 - 3 + 4 - \cdots - (x-2) + (x-1) - x$ $f(x) = f(x-1) - x$ Since $x$ is an odd number than $x - 1$ is an even number. And we know how to solve the problem for even numbers. Since $x$ is an odd number than $x - 1$ is an even number. And we know how to solve the problem for even numbers. But how do we calculate the sum of the elements on an arbitrary segment? Let's show that the sum of the elements of the array with indices from $l$ to $r$ inclusive is equal to $f(r) - f(l-1)$. Overall complexity $O(1)$.
|
[
"math"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
long long F(long long x)
{
if(x % 2 == 0)
return x / 2;
else
return -x + F(x-1);
}
int main()
{
int t;
cin >> t;
while(t--)
{
int l,r;
cin >> l >> r;
cout << F(r) - F(l-1) << '\n';
}
return 0;
}
|
1080
|
C
|
Masha and two friends
|
Recently, Masha was presented with a chessboard with a height of $n$ and a width of $m$.
The rows on the chessboard are numbered from $1$ to $n$ from bottom to top. The columns are numbered from $1$ to $m$ from left to right. Therefore, each cell can be specified with the coordinates $(x,y)$, where $x$ is the \textbf{column} number, and $y$ is the \textbf{row} number \textbf{(do not mix up)}.
Let us call a rectangle with coordinates $(a,b,c,d)$ a rectangle lower left point of which has coordinates $(a,b)$, and the upper right one — $(c,d)$.
The chessboard is painted black and white as follows:
\begin{center}
{\small An example of a chessboard.}
\end{center}
Masha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat — they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled \textbf{white} paint on the rectangle $(x_1,y_1,x_2,y_2)$. Then after him Denis spilled \textbf{black} paint on the rectangle $(x_3,y_3,x_4,y_4)$.
To spill paint of color $color$ onto a certain rectangle means that all the cells that belong to the given rectangle become $color$. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black).
Masha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers!
|
At first let's define a function $w(a,b)$, which returns the number of white cells on the subrectangle, the left bottom corner of which has coordinates $(1,1)$ and the top right one has coordinates $(a,b)$. (I will tell you how to implement the function later). How do we solve the problem using this function? Let's define functions $W(a,b,c,d)$ and $B(a,b,c,d)$, which return the number of white cells on the subrectangle which has coordinates $(a,b,c,d)$ and the number of black cells on the subrectangle which has coordinates $(a,b,c,d)$. (The definition of what we call the coordinates of a rectangle can be found in the statements) It can be easily proven that The value of $B(a,b,c,d)$ can be found as the number of all cells substracted by the number of the white cells: It means that in order to calculate the value of functions $W$ and $B$ efficiently it is enough to be able to calculate the value of $w$ efficiently. How de solve the problem using the funcitons defined above? Step 1. We should find the number of black cells and white cells in the initial chessboard (these values will be stored in the variables called $black$ and $white$ respectivly): Step 2. All the black cells in the rectangle $(x_1,y_1,x_2,y_2)$ will become white. So now: Step 3. Now all the white cells in the rectangle $(x_3,y_3,x_4,y_4)$ will become black. So now: But since the functions functions $B$ and $W$ return the number of cells black and white cells respectively in the initial board, so it isn't enough. What we did in the intersection of the rectangles: On step 2 we took the cells that were initially black and coloured them in white (everything is ok by now), but on step 3 we took only the cells that were initially white and coloured them in black. The cells that were initially black and coloured in white on step 2 were not coloured in black. In order to fix this we should find the rectangle which is an intersection of the rectangles $(x_1,y_2,x_2,y_2)$ and $(x_3,y_3,x_4,y_4)$, find the number of black cells in it and then colour them in black. It is obvious that the coordinates of the itersection of the rectangle are $(max(x_1,x_3), max(y_1,y_3), min(x_2,x_4), min(y_2, y_4))$. If $max(x_1,x_3) > min(x_2,x_4)$ or $max(y_1,y_3) > min(y_2, y_4)$ then there is no intersection, so we can just terminate the program. In another case we should apply: So we solved the task. Now it's time to tell how to implement function $w(a,b)$. Let's consider following chessboards from the examples: In order to explain more easily, I will name the pattern like this the pattern type 1 And the pattern like this the pattern type 2: It can be easily seen that if the number of rows is even, then the number of rows of both types is equal to $\frac{b}{2}$.If the number of rows is odd, then the number of rows of the type 2 is equal to $\Bigl\lceil \frac{b}{2} \Bigr\rceil$ and the number of rows of the type 1 is equal to $\Bigl\lfloor \frac{b}{2} \Bigr\rfloor$. Since $\Bigl\lceil \frac{b}{2} \Bigr\rceil = \Bigl\lfloor \frac{b}{2} \Bigr\rfloor$ if $b$ is even then we can just assume that the number of rows with pattern type 1 is $\Bigl\lfloor \frac{b}{2} \Bigr\rfloor$ and the number of rows with pattern type 2 is $\Bigl\lceil \frac{b}{2} \Bigr\rceil$. In the same way we can prove that the number of white cells in one row with pattern type 1 is equal to $\Bigl\lfloor \frac{a}{2} \Bigr\rfloor$ and in the pattern type 2 it is equal to $\Bigl\lceil \frac{a}{2} \Bigr\rceil$. So now: Overall complexity $O(1)$.
|
[
"implementation"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
long long cdiv(long long x, long long y)
{
return x / y + (x%y>0);
}
long long w(long long a, long long b)
{
return cdiv(a,2) * cdiv(b,2) + (a/2) * (b/2);
}
long long W(long long x1, long long y1, long long x2, long long y2)
{
return w(x2,y2) - w(x2,y1-1) - w(x1-1,y2) + w(x1-1,y1-1);
}
long long B(long long x1, long long y1, long long x2, long long y2)
{
return (y2 - y1 + 1) * (x2 - x1 + 1) - W(x1,y1,x2,y2);
}
int main()
{
int t;
cin >> t;
while(t--)
{
int x1,x2,x3,x4,y1,y2,y3,y4;
long long n, m;
cin >> n >> m ;
cin >>x1 >> y1 >>x2 >> y2 >> x3 >> y3 >> x4 >> y4;
long long white = W(1,1,m,n);
long long black = B(1,1,m,n);
// cout << white << ' ' << black << '\n';
white = white + B(x1,y1,x2,y2);
black = black - B(x1,y1,x2,y2);
//cout << white << ' ' << black << '\n';
white = white - W(x3,y3,x4,y4);
black = black + W(x3,y3,x4,y4);
if(max(x1,x3) <= min(x2,x4) && max(y1,y3) <= min(y2,y4))
{
white = white - B(max(x1,x3),max(y1,y3),min(x2,x4),min(y2,y4));
black = black + B(max(x1,x3),max(y1,y3),min(x2,x4),min(y2,y4));
}
cout << white << ' ' << black << '\n';
}
}
|
1080
|
D
|
Olya and magical square
|
Recently, Olya received a magical square with the size of $2^n\times 2^n$.
It seems to her sister that one square is boring. Therefore, she asked Olya to perform \textbf{exactly} $k$ splitting operations.
A Splitting operation is an operation during which Olya takes a square with side $a$ and cuts it into 4 equal squares with side $\dfrac{a}{2}$. If the side of the square is equal to $1$, then it is impossible to apply a splitting operation to it (see examples for better understanding).
Olya is happy to fulfill her sister's request, but she also wants the condition of Olya's happiness to be satisfied after all operations.
The condition of Olya's happiness will be satisfied if the following statement is fulfilled:
Let the length of the side of the lower left square be equal to $a$, then the length of the side of the right upper square should also be equal to $a$. There should also be a path between them that consists only of squares with the side of length $a$. All consecutive squares on a path should have a common side.
Obviously, as long as we have one square, these conditions are met. So Olya is ready to fulfill her sister's request only under the condition that she is satisfied too. Tell her: is it possible to perform exactly $k$ splitting operations in a certain order so that the condition of Olya's happiness is satisfied? If it is possible, tell also the size of the side of squares of which the path from the lower left square to the upper right one will consist.
|
At first let's check if the value of $k$ is not too large. This can be done greedily in the folllowing way: First splitting operation would be applied on the only existing inital square. After that we have $4$ squares with sides $2^{n-1}$. Now we will do $4$ spliiting operations each on one of them. Then we will have $16$ squares with sides $2^{n-2}$. If we repeat the action $n-1$ times we would end up having $4^n$ squares with size $1$. After that we can't do any more operations. Of course we don't do this manually - we just substract the number of splitting operations we did on each step from the number $k^{'}$ (that's the variable that is a copy of variable $k$ - we will need the value of $k$ later). If at some point of the algorithm we have to do more splitting operations than there remains to, then the value of $k$ is smaller than the maximum number of operations we can apply, thus $k$ is not too large, so we can just stop checking. If the algorithm successfuly did $n-1$ iterations and $k^{'}$ is still greater than $0$, it means that $k$ is greater than the maximum number of operations we can apply, so the answer is "NO". It can easily proven that for any $n > 30$ there are no too large numbers $k$ for them within the constraints of the task. Now we know that we can do $k$ operations, but can we do them in such a way the the condition of Olya's happiness is fuldilled? Let's imagine that the constraints are not so big and we can emulate the process. We can do it in the following way: Step 0. We split the only existing square. Step 1. If we can apply splitting opertation to all of the squares on the path from leftmost bottom point to rigthmost top point with the reamining operations, we should do it and after that we return to Step 1. Otherwise, the size of the squares of which the path consists is equal to the size of the squares the path consits now. Go to Step 2. Step 2. When we first did Step 1, we left one square of size $2^{n-1}$ untouched. All the remaining spliiting operations will be used in arbitrary way on it or the squares that appear from it. Let's prove that with relatively big $n$ we can always solve the problem with the following algorithm. If we can build the path from leftmost bottom point to rightmost top point with squares of size $2^0$ than everything is ok, since the remaining splitting operations can be done (we already checked that the value of $k$ is not too large). Otherwise, we can easily see that the number of squares to which you need to apply the splitting operation on each step changes like this: $3,7,15, \cdots$. It can be proven that the number of splitting operations on the $i$-th step is equal to: Let's assume that we stopped on $x$-th iteration of Step 1. It means that the number of splitting operations remaining is less than $4 * 2^{x-1} - 1$. It also means that we can do at least $1 + 4 + 16 + \cdots + 4^{x-1}$ operations on the $2^{n-1}$ square that was left untouched after the first iteration of the algorithm. Let's find the set of such numbers $x$ that $1 + 4 + 16 + \cdots + 4^{x-1}$ is greater or equal to $4 * 2^{x-1} - 1$: Since, in numerical system with base $4$ $1 + 4 + 16 + \cdots + 4^{x-1}$ can be represented as number with length $x+1$ that consists only of ones, it follows that: Now, back to our inequality: It's obvious that function $f_1(x) = 4^{x}$ grows faster than $f_2(x) = 12 * 2^{x-1} - 2$, so once the value of $f_1$ becomes greater than the value of $f_2$ it will never beome smaller. For $x = 3$: $f_1(3) = 4^{3} = 64$, $f_2(3) = 12 * 2^2 - 2 = 46, f_1(3) > f_2(3)$ For $x = 2$: $f_1(3) = 4^{2} = 16$, $f_2(3) = 12 * 2^1 - 2 = 22, f_1(2) < f_2(2)$ Now we know that the following algorithm always finds solution for all $n \ge 3$. The rest tests cases can be solved with if's, but still the algorithms works for them. The only exception is test "2 3" - there is no solution for this test, though $k$ is smaller than the maximum number of splitting operations you can apply. Like the first part of the solution we shouldn't do the algorthm manually - we can just on each step substract the length of the path from the variable $k$. (For $i$-th step it's $need_i$). Overall complexity $O(logn + logk)$.
|
[
"constructive algorithms",
"implementation",
"math"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
inline long long getLen(long long n, long long k)
{
long long divisions = 1;
k--;
long long len = 1;
while(divisions < n && k >= 4 * len - 1)
{
k -= 4 * len - 1;
len *= 2;
divisions++;
}
return n - divisions;
}
int main()
{
int t;
cin >> t;
while(t--)
{
long long n, k;
cin >> n >> k;
if(n==2 && k == 3)
{
cout << "NO\n";
continue;
}
long long _k = k, _n = n;
if(n <= 60)
{
long long pow4 = 1;
while(n--)
{
k -= pow4;
pow4 *= 4;
}
if(k > 0)
cout << "NO\n";
else
cout << "YES " << getLen(_n,_k) << "\n";
}
else
{
cout << "YES " << getLen(_n,_k) << "\n";
}
}
return 0;
}
|
1080
|
E
|
Sonya and Matrix Beauty
|
Sonya had a birthday recently. She was presented with the matrix of size $n\times m$ and consist of lowercase Latin letters. We assume that the rows are numbered by integers from $1$ to $n$ from bottom to top, and the columns are numbered from $1$ to $m$ from left to right.
Let's call a submatrix $(i_1, j_1, i_2, j_2)$ $(1\leq i_1\leq i_2\leq n; 1\leq j_1\leq j_2\leq m)$ elements $a_{ij}$ of this matrix, such that $i_1\leq i\leq i_2$ and $j_1\leq j\leq j_2$. Sonya states that a submatrix is beautiful if we can \textbf{independently} reorder the characters in each \textbf{row} (not in column) so that all \textbf{rows and columns} of this submatrix form palidroms.
Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings $abacaba, bcaacb, a$ are palindromes while strings $abca, acbba, ab$ are not.
Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix.
|
Suppose we have a submatrix and we want to check whether it is beautiful. First, each line must have a maximum of one character that occurs an odd number of times. Why is this enough to ensure that each line can be made a palindrome by reordering the characters in it? If there is exactly one character that occurs an odd number of times, then the string has an odd length and we can swap it with characters that stand in the central position of the string. All remaining characters can be paired and placed in opposite positions relative to the center of the line. Obviously, this condition is necessary. Also, in order for the submatrix to be beautiful, the following property must be satisfied: the opposing lines of the submatrix, relative to the central lines, must have the same content of characters, possibly in a different order. In other words, if the number of the first line of the submatrix is $i$, and the number of the last line of the submatrix is $j$, then for any integer $k$ $(0 \leq k\leq j-i)$ and for any character $c$ from 'a' to 'z' should be true, that the number of times that the character $c$ occurs in the line with the number $i+k$ coincides with the number of times the character $c$ occurs in the line with the number $j-k$. The necessity of this condition is based on the fact that after reordering characters independently in each row, our columns should turn out to be palindromes. To better understand this, see the explanation of the third example from the problem statement. Let us proceed to the solution of the problem: find the number of submatrices for which both of the above conditions are fulfilled. Fix the number of the first column of our submatrix. We will move the right column from the left one to the last one. So, what to do when we have two columns fixed. Let's define which strings can be palindromes, and which ones can't. To do this, we can support the auxiliary array $cnt[i][c]$ - how many times the character $c$ appears in the row with the number $i$. If the submatrix is beautiful, then each of its rows can be a palindrome, which means we can break our lines into groups of maximum size from consecutive lines that can be palindromes, and solve the puzzle for each group independently. Now we have the left and right columns of our submatrix, as well as a segment of consecutive lines, all of which can be palindromes. Then if we select any two rows and form a submatrix from these columns, rows and all rows between them, each row can be a palindrome, which means the first rule will always be fulfilled. It remains only to ensure that the second rule will be fulfilled. Let's break all strings into equivalence classes. In other words, we will give each line some number that will characterize the content of this line - the number of times how many letters each occur in this line. If two lines coincide in content, then they will have the same equivalence class, otherwise their classes will be different. For example, if we have a set of $4$ lines ${abac, ccab, bcaa, baab}$, then their classes will be ${1, 2, 1, 3}$, respectively. How can you find these classes? Previously, we created an array of $cnt[i][c]$, which stores the number of occurrences of each character in each row. We can encode this array with a single number - hash. What to do when we find equivalence class for each line? Let's look at some sub-line from a row of lines. More precisely, we will be interested only in the sequence of their equivalence classes. If our submatrix (formed by all elements on this segment and between the fixed columns) is good, then the equivalence classes of opposite rows are equal. So the sequence of classes on this segment will be a palindrome. So, we reduced the task to finding the number of palindromes on some sequence. This can be done using the Manacher's algorithm for $O(n)$ for each fixed pair of columns, or for $O(nlogn)$ using binary search and one more auxiliary array of hashes. More information about the mentioned topics can be found at the links listed below: Manacher's algorithm: https://cp-algorithms.com/string/manacher.html; Hashes: https://cp-algorithms.com/string/string-hashing.html; Equivalence classes: https://en.wikipedia.org/wiki/Equivalence_class;
|
[
"strings"
] | 2,400
|
# include <iostream>
# include <cmath>
# include <algorithm>
# include <stdio.h>
# include <cstdint>
# include <cstring>
# include <string>
# include <cstdlib>
# include <vector>
# include <bitset>
# include <map>
# include <queue>
# include <ctime>
# include <stack>
# include <set>
# include <list>
# include <random>
# include <deque>
# include <functional>
# include <iomanip>
# include <sstream>
# include <fstream>
# include <complex>
# include <numeric>
# include <immintrin.h>
# include <cassert>
# include <array>
# include <tuple>
# include <unordered_set>
# include <unordered_map>
using namespace std;
const long long md1=1e9+7;
const long long md2=1e9+87;
const long long key1=397,key2=419;
long long p1[600];
long long b[600];
int sz;
int n,m;
string s;
int a[605][605];
long long h[600];
int msk[600];
int cnt[610][50];
inline void init_hash() {
p1[0]=1;
for (int i=1;i<=500;++i)
p1[i]=(p1[i-1] * key1)%md1;
}
inline bool f_number(int x) {
return (bool) (x==0 || ((x&(x-1))==0));
}
int dp1[1005];
int dp2[1005];
inline long long solve(int i1,int i2) {
sz=0;
for (int i=i1;i<=i2;++i)
b[++sz]=h[i];
long long res=0;
int l=0,r=0,x;
for (int i=1;i<=sz;++i) {
if (i>r) x=1;
else x=min(dp1[l+r-i],r-i);
while (i-x>=1 && i+x<=sz && b[i-x]==b[i+x]) ++x;
dp1[i]=x;
if (i+x-1>r) l=i-x+1,r=i+x-1;
res+=x;
}
l=0,r=0;
for (int i=1;i<=sz;++i) {
if (i>r) x=0;
else x=min(dp2[l+r-i+1],r-i+1);
while (i-x-1>=1 && i+x<=sz && b[i-x-1]==b[i+x]) ++x;
dp2[i]=x;
res+=x;
if (i+x>=r) l=i-x,r=i+x-1;
}
return res;
}
int main(int argc, const char * argv[]) {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin>>n>>m;
for (int i=1;i<=n;++i) {
cin>>s;
for (int j=0;j<m;++j)
a[i][j+1]=(s[j]-'a');
}
init_hash();
long long x;
int i1,i2;
long long ans=0;
for (int j1=1;j1<=m;++j1) {
for (int i=1;i<=n;++i) {
msk[i]=0;
h[i]=0;
memset(cnt[i],0,sizeof(cnt[i]));
}
for (int j2=j1;j2<=m;++j2) {
for (int i=1;i<=n;++i) {
x=a[i][j2];
if (cnt[i][x]) {
h[i]-=(cnt[i][x] * p1[x+1])%md1;
if (h[i]<0) h[i]+=md1;
}
++cnt[i][x];
h[i]+=(cnt[i][x] * p1[x+1])%md1;
if (h[i]>=md1) h[i]-=md1;
msk[i]^=(1<<x);
}
i1=1;
while (i1<=n) {
if (!f_number(msk[i1])) {
++i1;
continue;
}
i2=i1;
while (i2<=n && f_number(msk[i2])) ++i2;
--i2;
ans+=solve(i1,i2);
i1=i2+1;
}
}
}
cout<<ans;
}
|
1080
|
F
|
Katya and Segments Sets
|
It is a very important day for Katya. She has a test in a programming class. As always, she was given an interesting problem that she solved very fast. Can you solve that problem?
You are given $n$ ordered segments sets. Each segment can be represented as a pair of two integers $[l, r]$ where $l\leq r$. Each set can contain an arbitrary number of segments (even $0$). It is possible that some segments are equal.
You are also given $m$ queries, each of them can be represented as four numbers: $a, b, x, y$. For each segment, find out whether it is true that each set $p$ ($a\leq p\leq b$) contains at least one segment $[l, r]$ that lies entirely on the segment $[x, y]$, that is $x\leq l\leq r\leq y$.
Find out the answer to each query.
Note that you need to solve this problem \textbf{online}. That is, you will get a new query only after you print the answer for the previous query.
|
Let's have an array in which we will store each segment and the number of the set to which it belongs. Sort this array in the non-decreasing order of the left border. If the left border is equal, we sort in random order. Now consider any query $a$ $b$ $x$ $y$. We should find the first position where the left border of the segment is greater than or equal to $x$. If there is no such position, then it is obvious that the answer will be "no", since there is no set that contains at least one suitable segment. Otherwise, we are interested only in the segments from the position that we have found to the last segment in the array. We can forget about the rest. Now let's among these segments for each set with a number from $a$ to $b$, find the minimum number $W$, such that there exists at least one segment that belongs to this set and its right bound is $W$ (note that we consider only those segments whose left bound is greater than or equal to $x$). If for some segment this number $W$ is greater than $y$, then the answer is "no". Otherwise the answer is "yes". Let's create a persistent segment tree, where for each set we keep its number $W$. We will update our $W$ values in reverse order - from the last segment to the first one. After hanging the value of the new $W$, we will save the current version in our segment tree. Then how to respond to requests? Let's find the position starting from which all the left borders of our segments will be at least $x$. After that, take the version of the persistent tree of segments that was added immediately after adding this segment. And in this segment tree, we take the minimum on the segment from $a$ to $b$. If our minimum is greater than $y$, then the answer is "no". Otherwise the answer is "yes".
|
[
"data structures",
"interactive",
"sortings"
] | 2,400
|
# include <iostream>
# include <cmath>
# include <algorithm>
# include <stdio.h>
# include <cstdint>
# include <cstring>
# include <string>
# include <cstdlib>
# include <vector>
# include <bitset>
# include <map>
# include <queue>
# include <ctime>
# include <stack>
# include <set>
# include <list>
# include <random>
# include <deque>
# include <functional>
# include <iomanip>
# include <sstream>
# include <fstream>
# include <complex>
# include <numeric>
# include <immintrin.h>
# include <cassert>
# include <array>
# include <tuple>
# include <unordered_set>
# include <unordered_map>
using namespace std;
const int inf=2e9;
const int N=100002;
const int K=300002;
int n,m,C,k;
int sz,all;
int lft[K*74],rght[K*74],t[K*74];
int root[K+5];
pair<pair<int,int>,int> seg[K+5];
inline void init_segment_tree() {
sz=1;
while (sz<n) sz+=sz;
all=sz+sz;
for (int i=1;i<sz;++i) {
lft[i]=i+i;
rght[i]=i+i+1;
}
for (int i=1;i<=all;++i)
t[i]=inf;
}
////////////////////////// SEGMENT TREE
inline int vcopy(int &x) {
++all;
lft[all]=lft[x];
rght[all]=rght[x];
t[all]=t[x];
return all;
}
void update(int l,int r,int ll,int x,int y) {
if (l==r) {
if (y<t[x]) t[x]=y;
return;
}
int mid=(l+r)>>1;
if (ll<=mid) {
lft[x]=vcopy(lft[x]);
update(l,mid,ll,lft[x],y);
} else {
rght[x]=vcopy(rght[x]);
update(mid+1,r,ll,rght[x],y);
}
y=t[lft[x]];
if (y<t[rght[x]]) y=t[rght[x]];
t[x]=y;
}
int get(int l,int r,int ll,int rr,int x) {
if (l>r || ll>r || l>rr || ll>rr) return 0;
if (l>=ll && r<=rr) return t[x];
int mid=(l+r)>>1;
return max(get(l,mid,ll,rr,lft[x]),get(mid+1,r,ll,rr,rght[x]));
}
//////////////////////////////////////////////////////////////////////
inline void build_segment_tree(int &C) {
root[C+1]=1;
for (int i=C;i>0;--i) {
root[i]=vcopy(root[i+1]);
update(1,sz,seg[i].second,root[i],seg[i].first.second);
}
}
inline int get_pos(int &x) {
int l=1,r=C;
int mid;
while (l<r-1) {
mid=(l+r)>>1;
if (seg[mid].first.first>=x) r=mid;
else l=mid;
}
if (seg[l].first.first>=x) r=l;
if (seg[r].first.first>=x) return r;
return C+1;
}
int main(int argc, const char * argv[]) {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin>>n>>m>>k;
int x,y,c;
for (int i=1;i<=k;++i) {
cin>>x>>y>>c;
seg[++C]=make_pair(make_pair(x,y),c);
}
init_segment_tree();
sort(seg+1,seg+C+1);
build_segment_tree(C);
int l, r, pos;
for (int i=1;i<=m;++i) {
cin>>l>>r>>x>>y;
pos=get_pos(x);
if (pos>C) {
cout<<"no"<<endl;
continue;
}
if (get(1,sz,l,r,root[pos])>y) cout<<"no";
else cout<<"yes";
cout<<endl;
}
}
|
1081
|
A
|
Definite Game
|
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.
He came up with the following game. The player has a positive integer $n$. Initially the value of $n$ equals to $v$ and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer $x$ that $x<n$ and $x$ is not a divisor of $n$, then subtract $x$ from $n$. The goal of the player is to minimize the value of $n$ in the end.
Soon, Chouti found the game trivial. Can you also beat the game?
|
1 sounds like the minimum value we can get. Why? Is it always true? When $n \le 2$, we can do nothing. When $n \ge 3$, since $1\,<\,\frac{n}{n-1}<2$, $n - 1$ isn't a divisor of $n$, so we can choose it and get $1$ as the result.
|
[
"constructive algorithms",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
scanf("%d", &n);
if (n == 2) {
puts("2");
} else {
puts("1");
}
return 0;
}
|
1081
|
B
|
Farewell Party
|
Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.
Chouti remembered that $n$ persons took part in that party. To make the party funnier, each person wore one hat among $n$ kinds of weird hats numbered $1, 2, \ldots n$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.
After the party, the $i$-th person said that there were $a_i$ persons wearing a hat \textbf{differing from his own}.
It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $b_i$ be the number of hat type the $i$-th person was wearing, Chouti wants you to find any possible $b_1, b_2, \ldots, b_n$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.
|
Consider the number of people wearing hats of the same color. let $b_{i} = n - a_{i}$ represent the number of people wearing the same type of hat of $i$-th person. Notice that the person wearing the same type of hat must have the same $b$s. Suppose the number of people having the same $b_{i}$ be $t$, there would be exactly $\frac{L}{b_{i}}$ kinds of hats with $b_{i}$ wearers. Therefore, $t$ must be a multiple of $b_{i}$. Also this is also sufficient, just give $b_{i}$ people a new hat color, one bunch at a time.
|
[
"constructive algorithms",
"implementation"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n;
pair<int,int> a[maxn];
int Ans[maxn],cnt;
int main(){
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i].first;
a[i].first=n-a[i].first;
a[i].second=i;
}
sort(a+1,a+n+1);
for(int l=1,r=0;l<=n;l=r+1){
for(r=l;r<n&&a[r+1].first==a[r].first;++r);
if((r-l+1)%a[l].first){
cout<<"Impossible"<<endl;
return 0;
}
for(int i=l;i<=r;i+=a[l].first){
cnt++;
for(int j=i;j<i+a[l].first;++j)Ans[a[j].second]=cnt;
}
}
cout<<"Possible"<<endl;
for(int i=1;i<=n;i++)cout<<Ans[i]<<' ';
return 0;
}
|
1081
|
C
|
Colorful Bricks
|
On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard.
There are $n$ bricks lined in a row on the ground. Chouti has got $m$ paint buckets of different colors at hand, so he painted each brick in one of those $m$ colors.
Having finished painting all bricks, Chouti was satisfied. He stood back and decided to find something fun with these bricks. After some counting, he found there are $k$ bricks with a color different from the color of the brick on its left (the first brick is not counted, for sure).
So as usual, he needs your help in counting how many ways could he paint the bricks. Two ways of painting bricks are different if there is at least one brick painted in different colors in these two ways. Because the answer might be quite big, you only need to output the number of ways modulo $998\,244\,353$.
|
No hint here :) Let $f[i][j]$ be the ways that there're $j$ bricks of a different color from its left-adjacent brick among bricks numbered $1$ to $i$. Considering whether the $i$-th brick is of the same color of $i - 1$-th, we have $f[i][j] = f[i - 1][j] + f[i - 1][j - 1](m - 1)$. $f[1][0] = m$ and the answer is $f[n][k]$. Also, there is a possibly easier solution. We can first choose the bricks of a different color from its left and then choose a different color to color them, so the answer can be found to be simply ${(binom{n-1}{k}}m(m-1)^{k}$.
|
[
"combinatorics",
"dp",
"math"
] | 1,500
|
//linear
#include <bits/stdc++.h>
using namespace std;
const int MOD=998244353;
typedef long long ll;
ll fac[2333],rfac[2333];
ll qp(ll a,ll b)
{
ll x=1; a%=MOD;
while(b)
{
if(b&1) x=x*a%MOD;
a=a*a%MOD; b>>=1;
}
return x;
}
int n,m,k;
int main()
{
scanf("%d%d%d",&n,&m,&k);
fac[0]=1;
for(int i=1;i<=n;++i)
fac[i]=fac[i-1]*i%MOD;
rfac[n]=qp(fac[n],MOD-2);
for(int i=n;i;--i)
rfac[i-1]=rfac[i]*i%MOD;
printf("%lld\n",m*qp(m-1,k)%MOD*fac[n-1]%MOD
*rfac[k]%MOD*rfac[n-1-k]%MOD);
}
|
1081
|
D
|
Maximum Distance
|
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.
You are given a connected undirected graph with $n$ vertices and $m$ weighted edges. There are $k$ special vertices: $x_1, x_2, \ldots, x_k$.
Let's define the cost of the path as the \textbf{maximum} weight of the edges in it. And the distance between two vertexes as the \textbf{minimum} cost of the paths connecting them.
For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.
The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.
|
Consider the MST of the graph. Consider the minimum spanning tree formed from the $n$ vertexes, we can find that the distance between two vertexes is the maximum weight of edges in the path between them in the minimum spanning tree (it's clear because of the correctness of Kruskal algorithm). Take any minimum spanning tree and consider some edge in this spanning tree. If this edge has all special vertexes on its one side, it cannot be the answer. Otherwise, it can always contribute to the answer, since for every special vertex, we can take another special vertex on the other side of this edge. Therefore, answers for all special vertexes are the maximum weight of the edges that have special vertexes on both sides. Besides implementing this directly, one can also run the Kruskal algorithm and maintain the number of special vertexes of each connected component in the union-find-set. Stop adding new edges when all special vertexes are connected together and the last edge added should be the answer.
|
[
"dsu",
"graphs",
"shortest paths",
"sortings"
] | 1,800
|
#include<bits/stdc++.h>
#define L long long
#define vi vector<int>
#define pb push_back
using namespace std;
int n,m,t,f[100010],p;
bool a[100010];
inline int fa(int i)
{
return f[i]==i?i:f[i]=fa(f[i]);
}
struct edge
{
int u,v,w;
inline void unit()
{
u=fa(u);
v=fa(v);
if(u!=v)
{
if(a[u])
f[v]=u;
else
f[u]=v;
if(a[u] && a[v])
p--;
if(p==1)
{
for(int i=1;i<=t;i++)
printf("%d ",w);
printf("\n");
exit(0);
}
}
}
}x[100010];
inline bool cmp(edge a,edge b)
{
return a.w<b.w;
}
int main()
{
int i,j;
scanf("%d%d%d",&n,&m,&t);
p=t;
for(i=1;i<=t;i++)
{
scanf("%d",&j);
a[j]=1;
}
for(i=1;i<=m;i++)
scanf("%d%d%d",&x[i].u,&x[i].v,&x[i].w);
sort(x+1,x+m+1,cmp);
for(i=1;i<=n;i++)
f[i]=i;
for(i=1;i<=m;i++)
x[i].unit();
return 0;
}
|
1081
|
E
|
Missing Numbers
|
Chouti is working on a strange math problem.
There was a sequence of $n$ positive integers $x_1, x_2, \ldots, x_n$, where $n$ is even. The sequence was very special, namely for every integer $t$ from $1$ to $n$, $x_1+x_2+...+x_t$ is a square of some integer number (that is, a perfect square).
Somehow, the numbers with odd indexes turned to be missing, so he is only aware of numbers on even positions, i.e. $x_2, x_4, x_6, \ldots, x_n$. The task for him is to restore the original sequence. Again, it's your turn to help him.
The problem setter might make mistakes, so there can be no possible sequence at all. If there are several possible sequences, you can output any.
|
How to solve $n = 2$? Let $s_{i}=\sum_{j=1}^{t}x_{j}=t_{i}^{2}$, $x_{max} = 2 \times 10^{5}$. Since $x_{2i} = s_{2i} - s_{2i - 1} = t_{2i}^{2} - t_{2i - 1}^{2} \ge (t_{2i - 1} + 1)^{2} - t_{2i - 1}^{2} = 2t_{2i - 1} + 1$, so $2t_{2i - 1} + 1 \le x_{max}$, $t_{2i - 1} < x_{max}$. For every $x\in[1,x_{m a x}]$, we can precalculate all possible $(a, b)$s so that $x = b^{2} - a^{2}$: enumerate all possible $a$ $\in[1,x_{m a x})$, then for every $a$ enumerate $b$ from small to large starting from $a + 1$ and stop when $b^{2} - a^{2} > x_{max}$, record this $(a, b)$ for $x = b^{2} - a^{2}$. Since $b^{2}-a^{2}=\sum_{i=a}^{b-1}(2i+1)\geq(2a+1)(b-a)$, then $b-a\leq{\frac{x_{m a z}}{2a+1}}\leq{\frac{x_{m a z}}{a}}$, its complexity is $O(x_{m a x}\log(x_{m a x}))$. Now, we can try to find a possible $s$ from left to right. Since $x_{2i - 1}$ is positive, we need to ensure $t_{2i - 2} < t_{2i - 1}$. Becuase $x_{2i} = t_{2i}^{2} - t_{2i - 1}^{2}$, we can try all precalculated $(a, b)$s such that $x_{2i} = b^{2} - a^{2}$. If we have several choices, we should choose the one that $a$ is minimum possible, because if the current sum is bigger, it will be harder for the remaining number to keep positive. Bonus: Solve $n \le 10^{3}$, $x_{2i} \le 10^{9}$. $t_{2i}^{2} - t_{2i - 1}^{2} = (t_{2i} - t_{2i - 1})(t_{2i} + t_{2i + 1})$. Factor $x_{2i}$.
|
[
"binary search",
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
vector<int> d[200099];
ll su[100099],x[100099];
int main()
{
for(int i=1;i<=200000;++i)
for(int j=i;j<=200000;j+=i)
d[j].push_back(i);
scanf("%d",&n);
for(int i=2;i<=n;i+=2)
scanf("%lld",x+i);
for(int i=2;i<=n;i+=2)
{
for(auto j:d[x[i]])
{
int a=j,b=x[i]/j;
if(((a+b)&1)||a>=b) continue;
int s1=(b-a)/2;
if(su[i-2]<(ll)s1*s1)
x[i-1]=(ll)s1*s1-su[i-2];
}
if(x[i-1]==0)
{
puts("No");
return 0;
}
su[i-1]=su[i-2]+x[i-1];
su[i]=su[i-1]+x[i];
}
puts("Yes");
for(int i=1;i<=n;i++)
printf("%lld%c",x[i]," \n"[i==n]);
}
|
1081
|
F
|
Tricky Interactor
|
\textbf{This is an interactive problem.}
Chouti was tired of studying, so he opened the computer and started playing a puzzle game.
Long long ago, the boy found a sequence $s_1, s_2, \ldots, s_n$ of length $n$, kept by a tricky interactor. It consisted of $0$s and $1$s only and the number of $1$s is $t$. The boy knows nothing about this sequence except $n$ and $t$, but he can try to find it out with some queries with the interactor.
We define an operation called flipping. Flipping $[l,r]$ ($1 \leq l \leq r \leq n$) means for each $x \in [l,r]$, changing $s_x$ to $1-s_x$.
In each query, the boy can give the interactor two integers $l,r$ satisfying $1 \leq l \leq r \leq n$ and the interactor will either flip $[1,r]$ or $[l,n]$ (both outcomes have the same probability and all decisions made by interactor are independent from each other, see Notes section for more details). The interactor will tell the current number of $1$s after each operation. Note, that the sequence \textbf{won't be restored} after each operation.
Help the boy to find the \textbf{original} sequence in no more than $10000$ interactions.
"Weird legend, dumb game." he thought. However, after several tries, he is still stuck with it. Can you help him beat this game?
|
What about parity? Assuming the number of $1$s changed from $a$ to $b$ after flipping a range of length $s$. Let the number of $1$s in the range before this flip be be $t$, then $b - a = (l - t) - t = s - 2t$, so $b-a\equiv s({\mathrm{mod}}\ 2)$. So if we made a query $l, r$, the parities of the lengths of $[1, r]$ and $[l, n]$ are different, we can find out which one is actually flipped by parity of delta. Also if we only want $[1, r]$ or $[l, n]$ to be flipped and nothing else, we can keep querying $l, r$ and record all the flips happened until it's the actual case (since flipping a range twice is equivalent to no flipping at all). The expected number of queries needed is $3$. Let $s_{a, b}$ be, currently $a \equiv $ the number of times $[1, r]$ is flipped $({\mathrm{mod}}\;2)$, $b \equiv $ the number of times $[r, n]$ is flipped $({\mathrm{mod}}\;2)$, the expectation of remaining number of queries needed to complete our goal. Then $s_{1, 0} = 0$ (goal), we're going to find out $s_{0, 0}$. $s_{0, 0} = (s_{0, 1} + s_{1, 0}) / 2 + 1, s_{0, 1} = (s_{0, 0} + s_{1, 1}) / 2 + 1, s_{1, 1} = (s_{1, 0} + s_{0, 1}) / 2 + 1$. Solve this equation you'll get $s_{0, 0} = 3, s_{0, 1} = 4, s_{1, 1} = 3$. Since $r\neq n-l+1{\mathrm{~(mod~2)}}\leftrightarrow r\equiv n-l{\mathrm{~(mod~2)}}\leftrightarrow r-l\equiv n{\mathrm{~(mod~2)}}$, it's easy to arrive at such arrangements. When $n\equiv0{\mathrm{~(mod~}}2{\mathrm{)}}$, try to query $(1, 1), (1, 1), (2, 2), (2, 2), (3, 3), (3, 3)...(n, n), (n, n)$ and use the method described above to flip $[1, 1], [1, 1], [1, 2], [1, 2], [1, 3], [1, 3]...[1, n], [1, n]$. Thus we'll know $s_{1}, s_{1} + s_{2}, s_{1} + s_{2} + s_{3}...s_{1} + s_{2} + ... + s_{n}$ and $s$ becomes obvious. When $n\equiv1{\pmod{2}}$, try to query $(2, n), (2, n), (1, 2), (1, 2), (2, 3), (2, 3)...(n - 1, n), (n - 1, n)$ and use the method described above to flip $[2, n], [2, n], [1, 2], [1, 2][1, 3], [1, 3]...[1, n], [1, n]$. Thus we'll know $s_{2} + s_{3} + ... + s_{n}, s_{1} + s_{2}, s_{1} + s_{2} + s_{3}...s_{1} + s_{2} + ... + s_{n}$ and $s$ also becomes obvious. Also, we can flip every range only once instead of twice by recording whether every element is currently flipped or not, although it will be a bit harder to write.
|
[
"constructive algorithms",
"implementation",
"interactive"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
int n,ss[10005],sn=0,q[333];
bool tf(int l,int r)
{
cout<<"? "<<l<<" "<<r<<endl<<flush;
cin>>ss[++sn];
return (ss[sn]-ss[sn-1])&1;
}
int main()
{
cin>>n>>ss[0]; q[n]=ss[0];
for(int i=1;i<n;++i)
{
int j=i-n%2;
if(j==0)
{
int t[2]={0,0},u=ss[sn];
while(t[0]!=1||t[1]!=0)
t[tf(2,n)]^=1;
int v=ss[sn];
q[i]=q[n]-(n-1-v+u)/2;
while(t[0]||t[1])
t[tf(2,n)]^=1;
}
else
{
int t[2]={0,0},u=ss[sn];
while(t[0]!=1||t[1]!=0)
t[(tf(j,i)^i)&1]^=1;
int v=ss[sn];
q[i]=(i-v+u)/2;
while(t[0]||t[1])
t[(tf(j,i)^i)&1]^=1;
}
}
cout<<"! ";
for(int i=1;i<=n;++i)
printf("%d",q[i]-q[i-1]);
cout<<endl<<flush;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.