Video failed to load

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

1293 words
6 minutes
Codeforces Round 162 (Div. 2) - A-E Editorial

A repeated theme in this round is replacing a long history by the small property the next transition actually needs. The final problem makes that compression explicit: a state remembers its last color, and two best distinct colors handle every switch.

This post covers every problem, A-E, from Codeforces Round 162 (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. Colorful Stones (Simplified Edition)implementation
B. Roadside Trees (Simplified Edition)greedy, implementation
C. Escape from Stonesgreedy, implementation
D. Good Sequencesdp, number theory
E. Choosing Ballsschedules, sortings

A picture of the main reduction#

Next ball: value v, color c

Continue dp[c] + a*v

Best other color + b*v

Start with b*v

Keep maximum; update top two colors

Next ball: value v, color c

Continue dp[c] + a*v

Best other color + b*v

Start with b*v

Keep maximum; update top two colors

A. Colorful Stones (Simplified Edition)#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Maintain the next stone index the squirrel needs. Read the instruction string once; advance the pointer only when the instruction equals that stone’s color. The final one-based pointer is the answer.

Why it works#

At every prefix of instructions the pointer records exactly how many required colors have been matched in order. A mismatching instruction leaves the state unchanged, while a matching instruction performs the single allowed advance. Induction over instructions establishes the simulation.

Complexity. O(|t|) time and O(|s|+|t|) storage.

Implementation check. The pointer is an index of the current stone, so output matched colors plus one.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
string s, t;
cin >> s >> t;
int p = 0;
for (char c : t)
if (p < (int)s.size() && s[p] == c)
p++;
cout << p + 1 << '\n';
}

B. Roadside Trees (Simplified Edition)#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

The squirrel must visit tree tops in their fixed order. Climbing the first tree costs h1h_1. Between consecutive tops, vertical movement costs ∣hi−hi−1∣|h_i-h_{i-1}|, regardless of whether it happens before or after the jump. There are n eating actions and n-1 jumps.

Why it works#

Each required top fixes the height at that moment, so the absolute height difference is an unavoidable lower bound on intervening vertical movement. Descend before jumping when the next tree is shorter, and climb after jumping when it is taller; this attains every lower bound.

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

Implementation check. There is no need to descend after eating the final nut.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n;
cin >> n;
ll prev = 0, ans = 2LL * n - 1;
for (int i = 0; i < n; i++) {
ll h;
cin >> h;
ans += llabs(h - prev);
prev = h;
}
cout << ans << '\n';
}

C. Escape from Stones#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Every new stone splits the remaining interval. If the squirrel escapes right, the stone just dropped lies before every future stone. If it escapes left, it lies after every future stone. Hence output all indices with instruction r in increasing order, then all indices with instruction l in decreasing order.

Why it works#

The earliest split fixes its stone’s position relative to all later stones. Removing that fixed extreme leaves exactly the same problem on a smaller interval. Repeatedly applying this observation puts right escapes at the front in insertion order and left escapes at the back in reverse insertion order.

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

Implementation check. Instructions describe the escape direction, not the direction in which to print the stone.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
string s;
cin >> s;
for (int i = 0; i < (int)s.size(); i++)
if (s[i] == 'r')
cout << i + 1 << '\n';
for (int i = (int)s.size() - 1; i >= 0; i--)
if (s[i] == 'l')
cout << i + 1 << '\n';
}

D. Good Sequences#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Factor each value into distinct primes. Let best[p] be the longest valid subsequence ending with a value divisible by p. A new value x extends the best state among its prime divisors. Compute its new length first, then update all its prime-divisor states.

Why it works#

Two positive integers have gcd greater than one exactly when they share a prime divisor. Therefore the prime-indexed states enumerate every possible compatible predecessor. Updating only after computing the maximum prevents the current element from extending itself through a different factor.

Complexity. O(V log log V+n log V) time using a smallest-prime-factor sieve, and O(V) space, with V=max(a).

Implementation check. The value 1 has no prime divisor, but still forms a subsequence of length one.

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);
for (int &x : a)
cin >> x;
int V = *max_element(a.begin(), a.end());
vector<int> spf(V + 1), best(V + 1);
for (int i = 2; i <= V; i++)
if (!spf[i])
for (int j = i; j <= V; j += i)
if (!spf[j])
spf[j] = i;
int ans = 1;
for (int x : a) {
vector<int> ps;
while (x > 1) {
int p = spf[x];
ps.push_back(p);
while (x % p == 0)
x /= p;
}
int cur = 1;
for (int p : ps)
cur = max(cur, best[p] + 1);
for (int p : ps)
best[p] = max(best[p], cur);
ans = max(ans, cur);
}
cout << ans << '\n';
}

E. Choosing Balls#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

For a query (a,b), keep dp[c], the best nonempty selected subsequence ending in color c. Taking a ball of value v and color c either continues color c for gain av, switches from another color for gain bv, or starts a new subsequence for gain bv.

Maintain the two largest dp values with different colors. The best state excluding c is then available in constant time. Keep the old dp[c] too, since skipping the ball is legal. The empty subsequence gives a final lower bound of zero.

Why it works#

Every selected subsequence ending at the current ball has either no previous ball, a previous ball of the same color, or one of a different color. These cases are disjoint and exhaust all transitions. The top-two structure answers the only cross-color maximum needed, and its two colors remain distinct.

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

Implementation check. Values and coefficients may be negative. Initialize nonempty states to negative infinity, not zero; only the explicit start transition may use an empty prefix.

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, q;
cin >> n >> q;
vector<ll> v(n);
vector<int> c(n);
for (ll &x : v)
cin >> x;
for (int &x : c)
cin >> x;
const ll NEG = -(1LL << 60);
while (q--) {
ll a, b;
cin >> a >> b;
vector<ll> dp(n + 1, NEG);
pair<ll, int> one = {NEG, -1}, two = one;
ll answer = 0;
for (int i = 0; i < n; i++) {
int col = c[i];
ll other = one.second == col ? two.first : one.first;
ll cur = max(dp[col], v[i] * b);
if (dp[col] != NEG)
cur = max(cur, dp[col] + v[i] * a);
if (other != NEG)
cur = max(cur, other + v[i] * b);
dp[col] = cur;
if (one.second == col)
one.first = cur;
else if (two.second == col) {
two.first = cur;
if (two > one)
swap(one, two);
} else if (cur > one.first) {
two = one;
one = {cur, col};
} else if (cur > two.first)
two = {cur, col};
answer = max(answer, cur);
}
cout << answer << '\n';
}
}

Support & Share

If this article helped you, please share or support!

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