Video failed to load

Codeforces Round 267 (Div. 2) - A-E Editorial

1505 words
8 minutes
Codeforces Round 267 (Div. 2) - A-E Editorial

Two useful greedy arguments anchor this round. Process replacement destinations from cheapest to most expensive, and commit an alternating block as soon as it can finish. Both choices become safe only after an exchange argument explains what they leave for the future.

This post covers every problem, A-E, from Codeforces Round 267 (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. George and Accommodationimplementation
B. Fedor and New Gamebitmasks, brute force, constructive algorithms
C. George and Jobdp, implementation
D. Fedor and Essaydfs and similar, dp, graphs
E. Alex and Complicated Taskdata structures, dp, greedy

A picture of the main reduction#

Equal pair: p, q

Store q at Fenwick index p

Current b; previous b at r

Query p less than r

q greater than r: p-r-q-current is ABAB

Commit earliest finish and clear current block

Equal pair: p, q

Store q at Fenwick index p

Current b; previous b at r

Query p less than r

q greater than r: p-r-q-current is ABAB

Commit earliest finish and clear current block

A. George and Accommodation#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Count rooms whose capacity exceeds their current occupancy by at least two.

Why it works#

The two friends can share a room exactly when that room has two free places. Rooms are independent choices, so summing this predicate gives the answer.

Complexity. O(n) time and O(1) auxiliary space.

Implementation check. Capacity minus occupancy, not capacity itself, is the available space.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n, ans = 0;
cin >> n;
while (n--) {
int p, q;
cin >> p >> q;
ans += q - p >= 2;
}
cout << ans << '\n';
}

B. Fedor and New Game#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

XOR each player’s army mask with Fedor’s mask. Its set bits mark exactly the unit types on which the armies differ. Count players whose XOR population count is at most k.

Why it works#

At each bit, XOR is one precisely when the two original bits differ. Therefore its number of ones is the required Hamming distance, and the given friendship condition becomes one comparison.

Complexity. O(m) machine-word operations and O(m) space here.

Implementation check. The final mask belongs to Fedor; do not count him among the other m players.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n, m, k;
cin >> n >> m >> k;
vector<unsigned> a(m + 1);
for (auto &x : a)
cin >> x;
int ans = 0;
for (int i = 0; i < m; i++)
ans += __builtin_popcount(a[i] ^ a[m]) <= k;
cout << ans << '\n';
}

C. George and Job#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Prefix sums give every length-m segment sum. Let dp[t][i] be the best total using exactly t segments among the first i elements. Either skip element i, or end a segment there and add its sum to dp[t-1][i-m]. Roll the segment-count dimension.

Why it works#

An optimal selection either has no segment ending at i or has a final segment [i-m,i). In the latter case every previous segment lies in the first i-m elements. The recurrence covers both possibilities without allowing overlap, and exactly-t initialization prevents silently choosing too few segments.

Complexity. O(nk) time and O(n) auxiliary space.

Implementation check. Unreachable states need negative infinity. A zero initialization for every t would solve an at-most-k variant instead.

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, m, k;
cin >> n >> m >> k;
vector<ll> p(n + 1);
for (int i = 1; i <= n; i++) {
ll x;
cin >> x;
p[i] = p[i - 1] + x;
}
const ll NEG = -(1LL << 60);
vector<ll> dp(n + 1, 0), next(n + 1);
for (int t = 1; t <= k; t++) {
fill(next.begin(), next.end(), NEG);
for (int i = 1; i <= n; i++) {
next[i] = next[i - 1];
if (i >= m && dp[i - m] != NEG)
next[i] = max(next[i], dp[i - m] + p[i] - p[i - m]);
}
dp.swap(next);
}
cout << dp[n] << '\n';
}

D. Fedor and Essay#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Normalize every word to lowercase and rank its cost by (number of r letters, length). Reverse each allowed replacement edge. Visit all words in increasing cost order; from an unassigned word, flood backward and assign its cost to every still-unassigned predecessor.

This is a multi-source propagation ordered by quality. A reverse-reachable word can eventually be replaced by the current source. Since sources are processed best first, its first assignment is optimal. No explicit SCC construction is needed, even when replacements contain cycles.

Why it works#

The first source reaching v is reachable from v in the original replacement graph. Any strictly better reachable source was processed earlier and would already have reached v, a contradiction. Skipping an assigned vertex is safe: all its reverse predecessors were reached during the earlier flood, so it cannot hide a new unassigned route.

Complexity. O(V log V+E+M) time and O(V+E+M) space, apart from word character processing.

Implementation check. Replacement edges are directed, and uppercase R counts too after normalization. Minimize r count first, then length.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
map<string, int> ids;
vector<pair<int, int>> cost;
vector<vector<int>> rev;
auto get = [&](string s) {
for (char &c : s)
c = tolower((unsigned char)c);
auto it = ids.find(s);
if (it != ids.end())
return it->second;
int id = ids.size();
ids[s] = id;
cost.push_back({count(s.begin(), s.end(), 'r'), s.size()});
rev.emplace_back();
return id;
};
int m;
cin >> m;
vector<int> essay(m);
for (int &id : essay) {
string s;
cin >> s;
id = get(s);
}
int e;
cin >> e;
while (e--) {
string a, b;
cin >> a >> b;
int u = get(a), v = get(b);
rev[v].push_back(u);
}
int n = ids.size();
vector<int> order(n);
iota(order.begin(), order.end(), 0);
sort(order.begin(), order.end(), [&](int a, int b) { return cost[a] < cost[b]; });
vector<bool> seen(n);
vector<pair<int, int>> best(n);
for (int source : order)
if (!seen[source]) {
vector<int> st{source};
seen[source] = true;
while (!st.empty()) {
int v = st.back();
st.pop_back();
best[v] = cost[source];
for (int u : rev[v])
if (!seen[u])
seen[u] = true, st.push_back(u);
}
}
ll r = 0, len = 0;
for (int v : essay) {
r += best[v].first;
len += best[v].second;
}
cout << r << ' ' << len << '\n';
}

E. Alex and Complicated Task#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

A valid answer consists of blocks a,b,a,ba,b,a,b, allowing a=ba=b. Take the first block that can finish, append it, and restart after its fourth position. An earlier finish leaves at least as much suffix as any competing first block.

To detect that finish efficiently, process equal-value pairs (p,q)(p,q) as they appear. A Fenwick tree indexed by p stores the greatest q and its value. When the current value is b and its previous occurrence is r, query pairs with p<r; a stored q>r gives p<r<q<current. Handle four equal values separately.

Why is the latest b sufficient? If a valid block used an older middle b while another b occurred after its third position, that other occurrence would have completed a block earlier, and the greedy scan would already have restarted.

Why it works#

The previous paragraph proves the detector finds the earliest possible finishing block, including the all-equal case. Replace the first block of any optimum by this earliest-finishing block: every later optimum block still fits after it. Induction on the remaining suffix proves the greedy concatenation optimal. Clear only touched Fenwick cells and touched values after a block to retain the complexity bound.

Complexity. O(n log n) time and O(n) space after value compression.

Implementation check. Reset the detector after each accepted block. Otherwise later blocks could reuse positions already printed.

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> a(n), xs;
for (int &x : a)
cin >> x;
xs = a;
sort(xs.begin(), xs.end());
xs.erase(unique(xs.begin(), xs.end()), xs.end());
vector<int> last(xs.size()), cnt(xs.size()), values, touched;
vector<pair<int, int>> bit(n + 1, {0, -1});
vector<int> ans;
for (int i = 1; i <= n; i++) {
int c = lower_bound(xs.begin(), xs.end(), a[i - 1]) - xs.begin();
if (cnt[c]++ == 0)
values.push_back(c);
int r = last[c];
pair<int, int> best = {0, -1};
for (int p = r - 1; p > 0; p -= p & -p)
best = max(best, bit[p]);
if (cnt[c] >= 4 || (r > 0 && best.first > r)) {
int first = cnt[c] >= 4 ? a[i - 1] : xs[best.second];
ans.insert(ans.end(), {first, a[i - 1], first, a[i - 1]});
for (int p : touched)
bit[p] = {0, -1};
touched.clear();
for (int v : values)
last[v] = cnt[v] = 0;
values.clear();
} else {
if (r)
for (int p = r; p <= n; p += p & -p) {
if (bit[p].first == 0)
touched.push_back(p);
bit[p] = max(bit[p], make_pair(i, c));
}
last[c] = i;
}
}
cout << ans.size() << '\n';
for (int x : ans)
cout << x << ' ';
cout << '\n';
}

Support & Share

If this article helped you, please share or support!

Sponsor
Codeforces Round 267 (Div. 2) - A-E Editorial
https://blog.wsh.moe/posts/cf-267-earliest-finish/
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