Idea: sunbrey
Tutorial
Tutorial is loading...
Solution
#include <iostream>
#include <vector>
using namespace std;
void solve() {
int l, a, b;
cin >> l >> a >> b;
vector<char> aubrey(l, false);
vector<char> sunny(l, false);
int cur = 0;
while (!aubrey[cur]) {
aubrey[cur] = true;
cur = (cur + a) % l;
}
cur = 0;
while (!sunny[cur]) {
sunny[cur] = true;
cur = (cur + b) % l;
}
int answer = 0;
for (int i = 0; i < l; ++i) {
if (aubrey[i] && sunny[i]) {
++answer;
}
}
cout << answer << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
Idea: sunbrey
Tutorial
Tutorial is loading...
Solution
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void solve() {
int n, k;
long long p;
cin >> n >> k >> p;
vector<long long> a(n);
long long total = 0;
for (long long &x : a) {
cin >> x;
total += x;
}
sort(a.begin(), a.end());
vector<long long> pref(n + 1, 0);
for (int i = 0; i < n; ++i) {
pref[i + 1] = pref[i] + a[i];
}
long long answer = total;
for (int glasses = 1; glasses <= n / k; ++glasses) {
long long fresh_sum = pref[glasses * k];
long long joy = total - fresh_sum + glasses * p;
answer = max(answer, joy);
}
cout << answer << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
2292C - Finding Shapes in the Clouds
Idea: sunbrey
Tutorial
Tutorial is loading...
Solution
#include <iostream>
#include <string>
using namespace std;
void solve() {
int n;
string s;
cin >> n >> s;
if (n % 2 == 1) {
cout << "NO\n";
return;
}
bool starts_with_zero = true;
bool starts_with_one = true;
for (int i = 0; i < n; ++i) {
char first = (i % 2 == 0 ? '0' : '1');
char second = (i % 2 == 0 ? '1' : '0');
if (s[i] != first) starts_with_zero = false;
if (s[i] != second) starts_with_one = false;
}
cout << (starts_with_zero || starts_with_one ? "NO\n" : "YES\n");
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
2292D - Unexpected Precipitation
Idea: sunbrey
Tutorial
Tutorial is loading...
Solution
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void solve() {
int n;
cin >> n;
vector<long long> x(n), y(n);
for (long long &value : x) cin >> value;
for (long long &value : y) cin >> value;
long long value = 0;
for (int i = n - 1; i >= 0; --i) {
long long delta = x[i] - y[i];
value = max(delta + value, -value);
}
if (value > 0) cout << "Sunny\n";
else if (value < 0) cout << "Aubrey\n";
else cout << "Draw\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
Idea: sunbrey
Tutorial
Tutorial is loading...
Solution
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
long long a, x, k;
cin >> a >> x >> k;
long long blocks = k + 1;
long long low = 0, high = 30 * blocks;
while (high - low > 1) {
long long rounds = (low + high) / 2;
long long q = rounds / blocks;
long long rem = rounds % blocks;
long long distance = (blocks + rem) * (1LL << q) - blocks;
if (distance < a + x * rounds) {
low = rounds;
} else {
high = rounds;
}
}
cout << a + x * low << '\n';
}
return 0;
}
Idea: sunbrey
Tutorial
Tutorial is loading...
Solution
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector<vector<int>> graph(2 * n);
vector<vector<int>> original(n);
vector<int> indegree(2 * n, 0);
for (int i = 0; i < m; ++i) {
int u, v, c;
cin >> u >> v >> c;
--u;
--v;
--c;
original[u].push_back(v);
original[v].push_back(u);
int from = 2 * u + c;
int to = 2 * v + (1 - c);
graph[from].push_back(to);
++indegree[to];
from = 2 * v + c;
to = 2 * u + (1 - c);
graph[from].push_back(to);
++indegree[to];
}
vector<int> component(n, -1);
int component_count = 0;
for (int start = 0; start < n; ++start) {
if (component[start] != -1) {
continue;
}
vector<int> stack = {start};
component[start] = component_count;
while (!stack.empty()) {
int v = stack.back();
stack.pop_back();
for (int u : original[v]) {
if (component[u] == -1) {
component[u] = component_count;
stack.push_back(u);
}
}
}
++component_count;
}
queue<int> q;
for (int v = 0; v < 2 * n; ++v) {
if (indegree[v] == 0) {
q.push(v);
}
}
while (!q.empty()) {
int v = q.front();
q.pop();
for (int u : graph[v]) {
--indegree[u];
if (indegree[u] == 0) {
q.push(u);
}
}
}
vector<char> good(component_count, false);
for (int v = 0; v < 2 * n; ++v) {
if (indegree[v] > 0) {
good[component[v / 2]] = true;
}
}
int answer = 0;
for (char is_good : good) {
answer += is_good;
}
cout << answer << '\n';
}
return 0;
}
Idea: sunbrey
Tutorial
Tutorial is loading...
Solution
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void solve() {
int m;
long long k;
cin >> m >> k;
vector<long long> a(m);
for (long long &value : a) cin >> value;
sort(a.begin(), a.end());
long long answer = 0;
for (int power = 1; (1 << power) <= m; ++power) {
int size = 1 << power;
vector<long long> coeff(size, 0);
coeff[size - 1] = power;
coeff[size - 2] = power - 2;
int index = size - 3;
for (int level = power - 1; level >= 1; --level) {
int count = 1 << (power - level);
for (int i = 0; i < count; ++i) {
if (index >= 0) {
coeff[index] = level - 2;
--index;
}
}
}
sort(coeff.begin(), coeff.end());
long long current = -1LL * (size - 1) * k;
int negative_count = 0;
int positive_count = 0;
for (long long value : coeff) {
if (value < 0) ++negative_count;
if (value > 0) ++positive_count;
}
for (int i = 0; i < negative_count; ++i) {
current += coeff[i] * a[i];
}
for (int i = 0; i < positive_count; ++i) {
current += coeff[size - positive_count + i] * a[m - positive_count + i];
}
answer = max(answer, current);
}
cout << answer << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
Idea: MikeMirzayanov
Tutorial
Tutorial is loading...
Solution
#include <iostream>
#include <vector>
struct Edge {
int left, right;
};
struct Difference {
int left, right;
};
std::vector<Difference> scan_log(const std::vector<Edge>& edges,
const std::vector<int>& calls, bool backward) {
const int m = static_cast<int>(calls.size());
std::vector<int> known(edges.size() + 1, 1);
std::vector<int> shared(edges.size(), 0);
std::vector<Difference> difference(m);
for (int step = 0; step < m; ++step) {
const int time = backward ? m - 1 - step : step;
const int id = calls[time];
const auto [u, v] = edges[id];
difference[time] = {known[u] - shared[id], known[v] - shared[id]};
const int combined = known[u] + difference[time].right;
known[u] = combined;
known[v] = combined;
shared[id] = combined;
}
return difference;
}
void solve() {
int n, m;
std::cin >> n >> m;
std::vector<Edge> edges(n - 1);
for (auto& [u, v] : edges) {
std::cin >> u >> v;
--u;
--v;
}
std::vector<int> calls(m);
for (int& id : calls) {
std::cin >> id;
--id;
}
const auto before = scan_log(edges, calls, false);
const auto after = scan_log(edges, calls, true);
for (int i = 0; i < m; ++i) {
const long long loss = 1LL * before[i].left * after[i].right
+ 1LL * before[i].right * after[i].left;
std::cout << loss << (i + 1 == m ? '\n' : ' ');
}
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int tests;
std::cin >> tests;
while (tests-- > 0) {
solve();
}
}








Why are there no comments?
Defintely the fastest editorial
one of the best rounds ive had the pleasure of solving! F and H felt soo hard :c
Glad you liked it !
Bad C
get good.
C is easy to be honest...
It's an observation problem. I took quite a long time though.
can anyone tell in question E test case a = 5 x = 1 k = 3 how 13 is coming because when i am dry running its comming 11 . I am checking if aubrey is smaller than sunny when aubrey reaches or exceeds sunny i am resetting v to 1 when k is not 0 if k reaches 0 then break
You get 13 instead of 11 because Sunny can give a compliment in a round before Aubrey reaches him, rather than waiting for her to catch up :3
thankyou
The answer $$$13$$$ can be achieved in the following way:
Round $$$1$$$: Sunny : $$$6$$$ Aubrey: $$$1$$$
Round $$$2$$$: Sunny: $$$7$$$ Aubrey: $$$3$$$
Round $$$3$$$: Sunny: $$$8$$$ Aubrey: $$$4$$$ (first compliment)
Round $$$4$$$: Sunny: $$$9$$$ Aubrey: $$$6$$$
Round $$$5$$$: Sunny: $$$10$$$ Aubrey: $$$7$$$ (second compliment)
Round $$$6$$$: Sunny: $$$11$$$ Aubrey: $$$9$$$
Round $$$7$$$: Sunny: $$$12$$$ Aubrey: $$$10$$$ (third compliment)
Round $$$8$$$: Sunny: $$$13$$$ Aubrey: $$$12$$$
Now in the next move Sunny's position will be $$$14$$$ and Aubrey's will be $$$16$$$, which is not desirable.
thankyou. I will give it a try
Great contest!
Thanks ! :3
How to improve in dp?
I loved solving F, very nice problem. Orz sunbrey
Problem H has an interesting linear algebraic interpretation:
We define $$$a_u$$$ to be the amount of information vertex $$$u$$$ has, and $$$b_e$$$ to be the total amount of information that has passed through edge $$$e$$$ so far (initially $$$0$$$).
We consider vectors of the form
$$$\displaystyle v = \begin{pmatrix} a_1 \cr \vdots \cr a_n \cr b_1 \cr \vdots \cr b_{n-1} \end{pmatrix}.$$$
Denote the initial state $$$a_u = 1, b_e = 0$$$ by $$$w$$$.
It is easy to see that each phone call acts linearly on this vector as $$$a_u, a_v, b_e \gets a_u + a_v - b_e$$$, so each operation can be written as a linear transformation $$$M_i$$$ such that the final state is
$$$\displaystyle M_m \cdots M_2 M_1 w.$$$
The sum of knowledge is then given by the dot product $$$\langle w, M_m \cdots M_2 M_1 w \rangle$$$.
A useful property of inner products is that $$$\langle x, Ay \rangle = x^\top Ay = \langle A^\top x, y \rangle$$$, which lets us rewrite this for any $$$i$$$ as
$$$\displaystyle \langle M_{i+1}^\top \cdots M_{m-1}^\top M_m^\top w, M_i \cdots M_2 M_1 w \rangle.$$$
The transpose of the matrix acts on vectors
$$$\displaystyle \begin{pmatrix} \alpha_1 \cr \vdots \cr \alpha_n \cr \beta_1 \cr \vdots \cr \beta_{n-1} \end{pmatrix}$$$
as $$$\alpha_u, \alpha_v \gets \alpha_u + \alpha_v + \beta_e$$$ and $$$\beta_e \gets -\alpha_u - \alpha_v - \beta_e$$$, which is exactly the original operation with the change of basis $$$\beta_e = -b_e$$$, so the left side of the inner product can be computed by simulating the operations backwards.
Of course, we can compute the transpose explicitly, but another way that is perhaps more useful in competitive programming is the "transposition principle," something which I first learned of through this AtCoder Algorithm Lectures article (Japanese only).
Returning to the problem, this transformation allows us to easily compute the amount of knowledge lost by losing call $$$i$$$, which is exactly
$$$\displaystyle \langle M_{i+1}^\top \cdots M_{m-1}^\top M_m^\top w, \left(M_i - I\right) M_{i-1} \cdots M_1 w \rangle.$$$
Note that $$$M_i - I$$$ is the transformation that sends every entry to $$$0$$$ except for
$$$\displaystyle \begin{array}{rl} a_u &\gets a_v - b_e \cr a_v &\gets a_u - b_e \cr b_e &\gets a_u + a_v - 2b_e \end{array}$$$
so it suffices to compute the dot product of these three entries of the left and right side, which can be performed in $$$\mathcal O(1)$$$ time.
Can someone explain me how do you comeup with the idea for label in problem C? I understood what it does and how it is used to prove that alternate strings can never be deleted completely. I just can't think of a thought process that could have comeup with this idea in middle of a contest.
Is it a general CP technique?
when u r solving a prob, the most important thing u should do is experiment with the prob
keep experimenting, and note observations which u can use to derive answer
in prob3, its pretty easy to notice that alternating string will always end up as either '01' or '10', and then it cant be simplified more
well what i did to get the answer was creating all bit strings of length 5, then observe them all.
I tried that. I experimented with n = 2, n = 4 and n = 6. I came to conclusion that alternating strings can't be removed completely but was not able to prove it.
oh actually lol even i have never proved my cp sol, so cant say anything about that
but yea when u r doing dp u always deep to prove ur sol, otherwise its optional
the key is do more practices like its
E and G lowkey easier than F and D
In C its proven that alternating strings are impossible, but why not for all other combinations? This isn't immediately obvious to me because a possible one can still be made impossible
My comment might help you understand that.
It is very helpful, should be part of this editorial, cheers
ahhhhh i overthought A i thought it was something lcd related god damn it
It actually can be solved with gcd and lcm of course
ans = l / lcm(gcd(a, l), gcd(b, l))
In the editorial I went through the simplest solution
Terrible $$$C$$$ + bad $$$E$$$, no one's sitting there proving these, just guess something and it passes.
both can be proved easily tho :/
is there an o(1) of o(logl) soln for first question?
Yes, ans = l / lcm(gcd(a, l), gcd(b, l))
One 0f the bad problem that I have ever seen
+
2292H — Пропущенный звонок Итоговая сумма равна числу упорядоченных пар (s,t) , для которых новость друга s дошла до друга t . Пропуск звонка может только уменьшить число таких пар.
Что передаётся по линии?
Рассмотрим звонок по линии uv . Пусть Ku и Kv — множества новостей у собеседников непосредственно перед звонком. Сразу после предыдущего звонка по этой линии оба друга знали одно и то же множество. Оно в точности равно Ku∩Kv . Действительно, удаление линии делит дерево на две части. Любая новость, которой собеседники ещё не обменялись, с тех пор могла дойти лишь до конца линии в своей части дерева. Перед первым звонком по этой линии пересечение пусто.
Значит, для обработки журнала достаточно счётчиков. Храним число новостей Su у каждого друга и число общих новостей Ce сразу после последнего звонка по каждой линии e . Изначально эти числа равны 1 и 0 соответственно. Перед звонком по линии e=uv запоминаем Fu=Su−Ce,Fv=Sv−Ce. Это количества новостей, которые сейчас впервые могут перейти через линию в каждом из двух направлений. По старым значениям вычислим Su+Sv−Ce и запишем результат в Su , Sv и Ce .
До кого ещё успеет дойти новость?
Зафиксируем звонок. Пусть Ru — множество друзей, до которых могла бы дойти новость из u , если использовать только звонки строго после выбранного. Сам друг u тоже входит в Ru . Аналогично определим Rv . Обработаем журнал тем же алгоритмом с конца, снова начав с одной новости у каждого друга. Если по некоторой цепочке звонков новость успевает дойти из u в t , то в обращённом журнале по той же цепочке в обратном порядке она дойдёт из t в u . Поэтому при обратном проходе для выбранного звонка получим величины Bu=|Ru∖Rv|,Bv=|Rv∖Ru|.
Чтобы новость друга s дошла до t через выбранный звонок из u в v , она должна успеть к u до звонка, а t должен быть достижим из v после него. Если v уже знал эту новость, то она может дождаться следующей передачи у v . Если до t можно добраться из u по последующим звонкам, то новость может остаться у u . Значит, пара может потеряться только при s∈Ku∖Kv и t∈Rv∖Ru .
Обратно, возьмём любые источник и получателя с этими свойствами. При наличии звонка новость доходит. Источник и получатель находятся по разные стороны линии uv . Чтобы обойтись без звонка, пришлось бы пересечь ту же линию раньше или позже. В первом случае друг v уже знал бы новость, во втором до t можно было бы добраться из u по последующим звонкам. Оба случая исключены. Если источник и получатель на одной стороне, эта линия им вообще не нужна: вместо выхода на другую сторону и возвращения новость может подождать.
В направлении из u в v теряется ровно FuBv пар. В противоположном направлении теряются другие пары, поэтому ответ для звонка равен FuBv+FvBu.
Сохраним по два значения прямого прохода для каждого звонка. При обратном проходе совместим их с двумя новыми значениями, используя прежний порядок концов ребра. Выведем ответы в хронологическом порядке. Время и память на один набор составляют O(n+m) . Для произведений и ответов нужны 64-битные целые числа.
I don't understand why i can't solve in general problems like C (which is the string binary + operations), how i can get better on those problems ?