Video failed to load

Codeforces Round 271 (Div. 2) - A-F Editorial

1702 words
9 minutes
Codeforces Round 271 (Div. 2) - A-F Editorial

The two final problems are useful exercises in choosing a query summary. A maximum length plus an endpoint reconstructs a pillar subsequence. A gcd plus occurrence positions identifies every surviving ant. Neither problem needs to retain the full set of candidates inside a segment-tree node.

This post covers every problem, A-F, from Codeforces Round 271 (Div. 2). 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#

ProblemFocus
A. Keyboardimplementation
B. Wormsbinary search, implementation
C. Captain Marmotbrute force, geometry
D. Flowersdp
E. Pillarsbinary search, data structures, dp
F. Ant colonydata structures, math, number theory

A picture of the main reduction#

Current height h

Query heights at most h-d

Query heights at least h+d

Best length plus one

Save predecessor; insert current index

Current height h

Query heights at most h-d

Query heights at least h+d

Best length plus one

Save predecessor; insert current index

A. Keyboard#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Locate each character in its keyboard row. If the hands shifted right, the intended character is one key left of the typed character; if shifted left, use the key on the right.

Why it works#

The stated shift acts independently at every keystroke. Reversing that shift on the same keyboard row gives the unique intended character. The input guarantees that this inverse neighbor exists.

Complexity. O(|s|) time and O(1) auxiliary space.

Implementation check. Reverse the physical shift when decoding.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
char dir;
string s;
cin >> dir >> s;
vector<string> rows = {"qwertyuiop", "asdfghjkl;", "zxcvbnm,./"};
for (char c : s)
for (auto row : rows) {
auto p = row.find(c);
if (p != string::npos)
cout << row[p + (dir == 'R' ? -1 : 1)];
}
cout << '\n';
}

B. Worms#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Replace pile sizes by their prefix sums. A worm numbered x belongs to the first pile whose cumulative sum is at least x, which is a lower-bound query.

Why it works#

Pile i contains exactly the worm numbers in the interval (prefix[i-1],prefix[i]]. These intervals are disjoint and cover all valid queries, so the first prefix at least x identifies the unique pile.

Complexity. O(n+q log n) time and O(n) space.

Implementation check. The query on the last worm of a pile stays in that pile, hence lower_bound rather than upper_bound.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> p(n);
for (int i = 0; i < n; i++) {
cin >> p[i];
if (i)
p[i] += p[i - 1];
}
int q;
cin >> q;
while (q--) {
int x;
cin >> x;
cout << lower_bound(p.begin(), p.end(), x) - p.begin() + 1 << '\n';
}
}

C. Captain Marmot#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

A point returns to its original position after four quarter-turns around its center. Enumerate the 444^4 rotation choices. For each resulting quadruple, sort its six squared pair distances: a square has four equal positive side distances and two equal diagonal distances, each twice a side distance.

Why it works#

The rotation choices cover every reachable configuration. The distance signature is sufficient: four equal shortest distances form the four sides, while the two larger equal distances are the diagonals. The factor-two relation forces right angles and the positivity check excludes coincident points.

Complexity. O(4^4) time and O(1) auxiliary space per test case.

Implementation check. Use squared 64-bit distances. The quarter-turn of (x,y) around (a,b) is (a-(y-b),b+(x-a)).

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct P {
ll x, y;
};
int main() {
int t;
cin >> t;
while (t--) {
P p[4], c[4], v[4][4];
for (int i = 0; i < 4; i++) {
cin >> p[i].x >> p[i].y >> c[i].x >> c[i].y;
v[i][0] = p[i];
for (int j = 1; j < 4; j++) {
auto a = v[i][j - 1];
v[i][j] = {c[i].x - (a.y - c[i].y), c[i].y + (a.x - c[i].x)};
}
}
int ans = 100;
for (int mask = 0; mask < 256; mask++) {
int z = mask, cost = 0;
P a[4];
for (int i = 0; i < 4; i++) {
int k = z % 4;
z /= 4;
cost += k;
a[i] = v[i][k];
}
vector<ll> d;
for (int i = 0; i < 4; i++)
for (int j = 0; j < i; j++) {
ll x = a[i].x - a[j].x, y = a[i].y - a[j].y;
d.push_back(x * x + y * y);
}
sort(d.begin(), d.end());
if (d[0] > 0 && d[0] == d[3] && d[4] == d[5] && d[4] == 2 * d[0])
ans = min(ans, cost);
}
cout << (ans == 100 ? -1 : ans) << '\n';
}
}

D. Flowers#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Count arrangements of each exact length: the last block is either a red block of length one or a white block of length k. Hence ways[i]=ways[i−1]+ways[i−k]ways[i]=ways[i-1]+ways[i-k], with ways[0]=1ways[0]=1 and a missing second term for i<k. Prefix sums answer every inclusive length interval.

Why it works#

Removing the last block partitions arrangements into two disjoint cases and leaves an arbitrary valid shorter arrangement. The recurrence is therefore bijective. Summing exact-length counts over [a,b] is the difference of the corresponding prefix sums.

Complexity. O(M+q) time and O(M) space, where M is the largest queried endpoint.

Implementation check. Keep ways[0]=1 for recurrence construction, but do not include length zero in positive-length query prefixes.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int q, k;
cin >> q >> k;
vector<pair<int, int>> queries(q);
int M = 0;
for (auto &[a, b] : queries) {
cin >> a >> b;
M = max(M, b);
}
const int MOD = 1000000007;
vector<int> w(M + 1), p(M + 1);
w[0] = 1;
for (int i = 1; i <= M; i++) {
w[i] = w[i - 1];
if (i >= k)
w[i] = (w[i] + w[i - k]) % MOD;
p[i] = (p[i - 1] + w[i]) % MOD;
}
for (auto [a, b] : queries)
cout << (p[b] - p[a - 1] + MOD) % MOD << '\n';
}

E. Pillars#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Process pillars in index order and compress their heights. For height h, a predecessor must have height at most h-d or at least h+d. A range-maximum tree answers those two ranges. Store a pair (length,last index), and remember a predecessor index for every new DP state to recover the actual subsequence.

Why it works#

Every legal subsequence ending at i has a previous index smaller than i, already inserted in the tree, and its height belongs to one of the two queried ranges. Conversely every returned state can legally append i. Induction proves the DP optimum; following saved predecessors reverses exactly its transitions.

Complexity. O(n log n) time and O(n) space.

Implementation check. Query before inserting the current pillar, particularly when d=0. Equal-height updates must retain the better length.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
ll d;
cin >> n >> d;
vector<ll> h(n), xs;
for (ll &x : h)
cin >> x;
xs = h;
sort(xs.begin(), xs.end());
xs.erase(unique(xs.begin(), xs.end()), xs.end());
int S = 1;
while (S < (int)xs.size())
S *= 2;
using V = pair<int, int>;
vector<V> tree(2 * S, {0, -1});
vector<int> pre(n, -1);
auto query = [&](int l, int r) {
V z = {0, -1};
for (l += S, r += S; l < r; l /= 2, r /= 2) {
if (l & 1)
z = max(z, tree[l++]);
if (r & 1)
z = max(z, tree[--r]);
}
return z;
};
V best = {0, -1};
for (int i = 0; i < n; i++) {
int a = upper_bound(xs.begin(), xs.end(), h[i] - d) - xs.begin(),
b = lower_bound(xs.begin(), xs.end(), h[i] + d) - xs.begin();
V v = max(query(0, a), query(b, xs.size()));
pre[i] = v.second;
v = {v.first + 1, i};
best = max(best, v);
int p = lower_bound(xs.begin(), xs.end(), h[i]) - xs.begin() + S;
tree[p] = max(tree[p], v);
for (p /= 2; p; p /= 2)
tree[p] = max(tree[p * 2], tree[p * 2 + 1]);
}
vector<int> path;
for (int i = best.second; i != -1; i = pre[i])
path.push_back(i + 1);
reverse(path.begin(), path.end());
cout << path.size() << '\n';
for (int i : path)
cout << i << ' ';
cout << '\n';
}

F. Ant colony#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

An ant survives exactly when its strength divides every strength in the interval. The surviving strength, if present, must equal the interval gcd: a present common divisor cannot be smaller than the gcd, because the gcd also divides that present value.

Use an iterative gcd segment tree, and store the sorted occurrence indices of every value. A query returns interval length minus the number of occurrences of its gcd, found by two binary searches.

Why it works#

If a value equals the interval gcd, it divides all entries and survives. Conversely a surviving present value divides the gcd, while the gcd divides every present value, so they are equal. This characterizes survivors completely and proves the subtraction formula.

Complexity. O((n+q) log n) time and O(n) space.

Implementation check. The gcd may not appear in the range at all; then every ant is eliminated.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> t(2 * n);
map<int, vector<int>> pos;
for (int i = 0; i < n; i++) {
cin >> t[n + i];
pos[t[n + i]].push_back(i);
}
for (int i = n - 1; i; i--)
t[i] = gcd(t[i * 2], t[i * 2 + 1]);
int q;
cin >> q;
while (q--) {
int l, r;
cin >> l >> r;
--l;
int g = 0;
for (int a = l + n, b = r + n; a < b; a /= 2, b /= 2) {
if (a & 1)
g = gcd(g, t[a++]);
if (b & 1)
g = gcd(g, t[--b]);
}
auto it = pos.find(g);
int count = 0;
if (it != pos.end()) {
auto &v = it->second;
count = lower_bound(v.begin(), v.end(), r) - lower_bound(v.begin(), v.end(), l);
}
cout << r - l - count << '\n';
}
}

Support & Share

If this article helped you, please share or support!

Sponsor
Codeforces Round 271 (Div. 2) - A-F Editorial
https://blog.wsh.moe/posts/cf-271-queries-and-reconstruction/
Author
Wsh
Published at
2026-10-24

Comments

LEAVE A NOTE

Join the conversation

Markdown supported

Be kind. Good conversations start with you.

Conversation

Loading conversation…

Comments powered by Waline

Profile Image of the Author
Wsh
Nice to meet you! Hello, I'm Wsh.
Announcement
Any news or updates will be shared here, so check back anytime! Thanks for stopping by, meow >.<
Categories
Tags
Site Statistics
Posts
27
Categories
7
Tags
69
Total Words
124,615
Running Days
0 days
Last Activity
0 days ago
Site Info
Build Platform
Vercel
Blog Version
Firefly v6.16.8
License
CC BY-NC-SA 4.0
Table of Contents