Codeforces Round 250 (Div. 1) - A-E Editorial
- 1Codeforces Round 162 (Div. 2) - A-E Editorial
- 2Codeforces Round 250 (Div. 1) - A-E EditorialThis article
- 3Codeforces Round 256 (Div. 2) - A-E Editorial
- 4Codeforces Round 267 (Div. 2) - A-E Editorial
- 5Codeforces Round 271 (Div. 2) - A-F Editorial
- 6Codeforces Round 277.5 (Div. 2) - A-F Editorial
- 7Codeforces Round 316 (Div. 2) - A-E Editorial
- 8Codeforces Round 324 (Div. 2) - A-E Editorial
- 9Codeforces Round 388 (Div. 2) - A-E Editorial
- 10Codeforces Round 546 (Div. 2) - A-E Editorial

This Div. 1 set moves from edgewise lower bounds to algebraic Newton iteration. Its geometry problem requires a simple polygon, not a convex one, and its last problem counts entire families of weighted binary trees. Those two details are where a plausible shortcut becomes a wrong solution.
This post covers every problem, A-E, from Codeforces Round 250 (Div. 1). Each section contains a self-contained C++17 solution and its reasoning. The shorter opening problems are included so that the round is complete; the later sections carry the deeper techniques.
Round map
| Problem | Focus |
|---|---|
| A. The Child and Toy | greedy, sortings |
| B. The Child and Zoo | dp, dsu, sortings |
| C. The Child and Polygon | dp, geometry |
| D. The Child and Sequence | data structures, math |
| E. The Child and Binary Tree | combinatorics, divide and conquer, fft |
A picture of the main reduction
A. The Child and Toy
Problem statement · Download the complete C++17 solution
Derive the algorithm
Charge each graph edge when its first endpoint is removed. That charge is the weight of its still-present endpoint, hence at least the smaller endpoint weight. Remove vertices in decreasing weight order to attain the smaller weight on every edge simultaneously. The answer is the sum of min(wu,wv) over all edges.
Why it works
Each edge contributes exactly once, so summing its independent lower bound is a lower bound on total cost. The descending-weight removal order attains all these bounds at once, proving the sum optimal without needing to simulate removals.
Complexity. O(n+m) time and O(n) space.
Implementation check. The removal cost counts neighbors still present, not the removed vertex itself.
C++17
#include <bits/stdc++.h>using namespace std;using ll = long long;
int main() { int n, m; cin >> n >> m; vector<ll> w(n); for (ll &x : w) cin >> x; ll ans = 0; while (m--) { int u, v; cin >> u >> v; ans += min(w[u - 1], w[v - 1]); } cout << ans << '\n';}B. The Child and Zoo
Problem statement · Download the complete C++17 solution
Derive the algorithm
Give edge (u,v) weight min(au,av). A path’s minimum edge weight equals its minimum vertex weight. Process edges in decreasing weight order with DSU. When an edge of weight w joins components of sizes x and y, exactly xy pairs become connected for the first time and have maximum bottleneck w.
Accumulate wxy and divide by the number of unordered pairs. Ordered pairs give the same average because each unordered pair appears twice.
Why it works
Before weight w is processed, DSU connectivity records paths with strictly larger bottleneck, along with any already processed equal-weight edges. Newly connected pairs have a path of bottleneck w and had no better one. Each pair is charged on its unique first merge, so the accumulated value is precisely the bottleneck sum.
Complexity. O(m log m+m alpha(n)) time and O(n+m) space.
Implementation check. Multiply component sizes in 64-bit arithmetic before multiplying the weight, then convert the final sum to floating point.
C++17
#include <bits/stdc++.h>using namespace std;using ll = long long;
struct DSU { vector<int> p; vector<ll> s; DSU(int n) : p(n), s(n, 1) { iota(p.begin(), p.end(), 0); } int find(int x) { while (p[x] != x) x = p[x] = p[p[x]]; return x; }};int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; vector<int> a(n); for (int &x : a) cin >> x; vector<tuple<int, int, int>> edges; while (m--) { int u, v; cin >> u >> v; --u; --v; edges.push_back({min(a[u], a[v]), u, v}); } sort(edges.rbegin(), edges.rend()); DSU d(n); ll total = 0; for (auto [w, u, v] : edges) { u = d.find(u); v = d.find(v); if (u == v) continue; total += 1LL * w * d.s[u] * d.s[v]; if (d.s[u] < d.s[v]) swap(u, v); d.p[v] = u; d.s[u] += d.s[v]; } cout << fixed << setprecision(12) << (long double)total / (1LL * n * (n - 1) / 2) << '\n';}C. The Child and Polygon
Problem statement · Download the complete C++17 solution
Derive the algorithm
The polygon need not be convex. First determine which vertex pairs are legal sides of a triangle: boundary neighbors are allowed; a diagonal must contain no other polygon vertex, cross no nonincident boundary edge, and have its midpoint strictly inside the polygon.
Then let dp[l][r] count triangulations of the chain l through r closed by the legal segment (l,r). Choose the third vertex k of the triangle incident to that closing segment. Multiply dp[l][k] and dp[k][r], requiring all triangle edges legal and a nonzero triangle with the polygon’s orientation.
Use exact integer cross products. Midpoints can also be represented exactly by doubling all polygon coordinates and using the sum of the two endpoint coordinates as the query point.
Why it works
A valid triangulation has a unique triangle incident to its closing side. Its third vertex splits the remaining region into the two disjoint subpolygons in the recurrence. Conversely, legal interior diagonals and correctly oriented nondegenerate triangles join two subpolygon triangulations into one valid triangulation. The diagonal checks rule out boundary crossings, edges through other vertices, and exterior chords, covering the concave and collinear cases.
Complexity. O(n^3) time and O(n^2) space.
Implementation check. A convex-polygon Catalan recurrence alone is wrong here. Reversing clockwise input simplifies every orientation check.
C++17
#include <bits/stdc++.h>using namespace std;using ll = long long;
struct P { ll x, y; P operator-(P b) const { return {x - b.x, y - b.y}; }};ll cross(P a, P b) { return a.x * b.y - a.y * b.x;}ll orient(P a, P b, P c) { return cross(b - a, c - a);}bool on(P a, P b, P c) { return orient(a, b, c) == 0 && min(a.x, b.x) <= c.x && c.x <= max(a.x, b.x) && min(a.y, b.y) <= c.y && c.y <= max(a.y, b.y);}bool opposite(ll a, ll b) { return (a < 0 && b > 0) || (a > 0 && b < 0);}int main() { int n; cin >> n; vector<P> p(n); for (auto &a : p) cin >> a.x >> a.y; ll area = 0; for (int i = 0; i < n; i++) area += cross(p[i], p[(i + 1) % n]); if (area < 0) reverse(p.begin(), p.end()); auto inside = [&](P q) { bool in = false; for (int i = 0; i < n; i++) { P a = {2 * p[i].x, 2 * p[i].y}, b = {2 * p[(i + 1) % n].x, 2 * p[(i + 1) % n].y}; if (on(a, b, q)) return false; ll c = orient(a, b, q); if ((a.y <= q.y && q.y < b.y && c > 0) || (b.y <= q.y && q.y < a.y && c < 0)) in = !in; } return in; }; vector<vector<bool>> ok(n, vector<bool>(n)); for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { if (j == i + 1 || (i == 0 && j == n - 1)) { ok[i][j] = ok[j][i] = true; continue; } bool good = true; for (int k = 0; k < n; k++) if (k != i && k != j && on(p[i], p[j], p[k])) good = false; for (int k = 0; k < n; k++) { int z = (k + 1) % n; if (k == i || k == j || z == i || z == j) continue; if (opposite(orient(p[i], p[j], p[k]), orient(p[i], p[j], p[z])) && opposite(orient(p[k], p[z], p[i]), orient(p[k], p[z], p[j]))) good = false; } if (good) good = inside({p[i].x + p[j].x, p[i].y + p[j].y}); ok[i][j] = ok[j][i] = good; } const ll MOD = 1000000007; vector<vector<ll>> dp(n, vector<ll>(n)); for (int i = 0; i + 1 < n; i++) dp[i][i + 1] = 1; for (int len = 2; len < n; len++) for (int l = 0; l + len < n; l++) { int r = l + len; if (!ok[l][r]) continue; for (int k = l + 1; k < r; k++) if (ok[l][k] && ok[k][r] && orient(p[l], p[k], p[r]) > 0) dp[l][r] = (dp[l][r] + dp[l][k] * dp[k][r]) % MOD; } cout << dp[0][n - 1] << '\n';}D. The Child and Sequence
Problem statement · Download the complete C++17 solution
Derive the algorithm
A sum tree alone cannot lazily update a segment modulo x. Add the segment maximum: if it is below x, every value is unchanged, so prune the entire subtree. Otherwise descend, apply modulo at affected leaves, and rebuild sums and maxima. Point assignment and range sum are ordinary tree operations.
Why it works
The maximum check is an exact no-change certificate. At a changed leaf, v mod x is less than v/2: if x<=v/2 the remainder is below x, and otherwise the quotient is one and the remainder is v-x. Thus each effective visit consumes a unit of logarithmic value potential; point assignments are the only operations that refill it.
Complexity. O((n+q) log A log n) amortized time for values bounded by A, and O(n) space.
Implementation check. The modulo threshold is positive. Track maxima after point assignments as well as modulo changes.
C++17
#include <bits/stdc++.h>using namespace std;using ll = long long;
struct Tree { int n; vector<ll> s, mx; Tree(vector<ll> &a) : n(a.size()), s(4 * n), mx(4 * n) { build(1, 0, n, a); } void pull(int v) { s[v] = s[v * 2] + s[v * 2 + 1]; mx[v] = max(mx[v * 2], mx[v * 2 + 1]); } void build(int v, int l, int r, vector<ll> &a) { if (r - l == 1) { s[v] = mx[v] = a[l]; return; } int m = (l + r) / 2; build(v * 2, l, m, a); build(v * 2 + 1, m, r, a); pull(v); } void change(int v, int l, int r, int a, int b, ll x, bool assignment) { if (b <= l || r <= a || (!assignment && mx[v] < x)) return; if (r - l == 1) { s[v] = mx[v] = assignment ? x : s[v] % x; return; } int m = (l + r) / 2; change(v * 2, l, m, a, b, x, assignment); change(v * 2 + 1, m, r, a, b, x, assignment); pull(v); } ll sum(int v, int l, int r, int a, int b) { if (b <= l || r <= a) return 0; if (a <= l && r <= b) return s[v]; int m = (l + r) / 2; return sum(v * 2, l, m, a, b) + sum(v * 2 + 1, m, r, a, b); }};int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, q; cin >> n >> q; vector<ll> a(n); for (ll &x : a) cin >> x; Tree st(a); while (q--) { int type, l, r; ll x; cin >> type; if (type == 1) { cin >> l >> r; cout << st.sum(1, 0, n, l - 1, r) << '\n'; } else if (type == 2) { cin >> l >> r >> x; st.change(1, 0, n, l - 1, r, x, false); } else { cin >> l >> x; st.change(1, 0, n, l - 1, l, x, true); } }}E. The Child and Binary Tree
Problem statement · Download the complete C++17 solution
Derive the algorithm
Let C(x) indicate the allowed positive node weights, and let F(x) count ordered rooted binary trees, including the empty tree. A nonempty tree chooses a root weight and independently chooses its left and right subtrees, giving
Instead of introducing a formal square root, apply Newton directly to . If f is correct modulo , compute
The denominator has constant term one because C(0)=0. It therefore has a formal inverse. Use NTT multiplication and polynomial inversion at each doubling step; truncate all intermediates to the new precision.
Why it works
Expanding H(f+delta) gives H(f)+(1-2Cf)delta-C delta^2. The Newton correction cancels the first two terms. Since H(f) is divisible by x^s, the correction is too, and its squared term vanishes modulo x^(2s). Starting at f=1 therefore doubles the number of correct coefficients until every requested coefficient is known. The root decomposition uniquely specifies the series with constant term one.
Complexity. O(m log m) time with geometric precision doubling and NTT multiplication; O(m) working space.
Implementation check. An absent child is the empty tree, so F[0]=1. Ignore allowed weights above m, but never insert a weight-zero node. This standalone file includes its NTT and inversion helpers.
C++17
#include <bits/stdc++.h>using namespace std;using ll = long long;
constexpr int mod = 998244353;using Poly = std::vector<int>;inline int power(int a, long long e) { int r = 1; for (; e; e >>= 1, a = int(1LL * a * a % mod)) if (e & 1) r = int(1LL * r * a % mod); return r;}inline void ntt(Poly &a, bool inverse) { int n = int(a.size()); if (n == 0 || (n & (n - 1)) || n > (1 << 23)) throw std::invalid_argument("NTT length must be a power of two <= 2^23"); for (int i = 1, j = 0; i < n; ++i) { int bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) std::swap(a[i], a[j]); } for (int len = 2; len <= n; len <<= 1) { int root = power(3, (mod - 1) / len); if (inverse) root = power(root, mod - 2); for (int start = 0; start < n; start += len) { int w = 1; for (int j = 0; j < len / 2; ++j) { int u = a[start + j]; int v = int(1LL * a[start + j + len / 2] * w % mod); a[start + j] = (u + v) % mod; a[start + j + len / 2] = (u - v + mod) % mod; w = int(1LL * w * root % mod); } } } if (inverse) { int inv = power(n, mod - 2); for (int &x : a) x = int(1LL * x * inv % mod); }}inline Poly multiply(Poly a, Poly b) { if (a.empty() || b.empty()) return {}; int need = int(a.size() + b.size() - 1), n = 1; while (n < need) n <<= 1; a.resize(n); b.resize(n); ntt(a, false); ntt(b, false); for (int i = 0; i < n; ++i) a[i] = int(1LL * a[i] * b[i] % mod); ntt(a, true); a.resize(need); return a;}inline Poly inverse(const Poly &a, int n) { if (n <= 0) return {}; if (a.empty() || a[0] == 0) throw std::invalid_argument("Nonzero constant required"); Poly b{power(a[0], mod - 2)}; while (int(b.size()) < n) { int m = std::min(n, 2 * int(b.size())); Poly prefix(a.begin(), a.begin() + std::min(m, int(a.size()))); Poly e = multiply(prefix, b); e.resize(m); for (int &x : e) x = x ? mod - x : 0; e[0] = (e[0] + 2) % mod; b = multiply(b, e); b.resize(m); } return b;}
int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; Poly C(m + 1); for (int i = 0, x; i < n; i++) { cin >> x; if (x <= m) C[x] = 1; } Poly f{1}; while ((int)f.size() < m + 1) { int len = min(m + 1, 2 * (int)f.size()); Poly c(C.begin(), C.begin() + len), ff = multiply(f, f), h = multiply(c, ff), cf = multiply(c, f); h.resize(len); cf.resize(len); Poly den(len); for (int i = 0; i < len; i++) { int fi = i < (int)f.size() ? f[i] : 0; h[i] = (fi - h[i] + mod) % mod; den[i] = (mod - 2LL * cf[i] % mod) % mod; } h[0] = (h[0] + mod - 1) % mod; den[0] = (den[0] + 1) % mod; Poly correction = multiply(h, inverse(den, len)); correction.resize(len); f.resize(len); for (int i = 0; i < len; i++) f[i] = (f[i] - correction[i] + mod) % mod; } for (int i = 1; i <= m; i++) cout << f[i] << '\n';}Support & Share
If this article helped you, please share or support!




























































Conversation
Comments powered by Waline