Video failed to load

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

1570 words
8 minutes
Codeforces Round 316 (Div. 2) - A-E Editorial

The two palindrome problems have different sources of difficulty. Tree Requests asks whether a multiset can be rearranged, so parity is sufficient. Pig and Palindromes fixes path order, so the state must synchronize two ends of the path. Distinguishing those requirements is the central lesson of this round.

This post covers every problem, A-E, from Codeforces Round 316 (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. Electionsimplementation
B. Simple Gameconstructive algorithms, games, greedy
C. Replacementconstructive algorithms, data structures, implementation
D. Tree Requestsbinary search, bitmasks, constructive algorithms
E. Pig and Palindromescombinatorics, dp

A picture of the main reduction#

Yes

Front at step t: r1, c1

Same letter as back?

Back at step t: r2, c2

Four paired moves

Meet or become adjacent at middle

Yes

Front at step t: r1, c1

Same letter as back?

Back at step t: r2, c2

Four paired moves

Meet or become adjacent at middle

A. Elections#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

For each city, find the candidate with the most votes there. Give that candidate one city win. Then find the candidate with the most city wins. Both ties go to the smaller candidate index, so scan candidates from left to right and replace the winner only on a strict improvement.

Why it works#

The election rule makes each city an independent comparison. The first maximum encountered is exactly the smallest index among tied candidates. Applying the same rule to the accumulated city wins therefore implements both levels of the election.

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

Implementation check. The answer is not the candidate with the greatest sum of votes.

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;
cin >> n >> m;
vector<int> wins(n);
for (int city = 0; city < m; city++) {
int best = -1, who = 0;
for (int i = 0, x; i < n; i++) {
cin >> x;
if (x > best)
best = x, who = i;
}
wins[who]++;
}
cout << max_element(wins.begin(), wins.end()) - wins.begin() + 1 << '\n';
}

B. Simple Game#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Choose a position next to the opponent’s position mm. Choosing m−1m-1 wins the m−1m-1 locations on the left; choosing m+1m+1 wins the n−mn-m locations on the right. Take the larger side, with a boundary check when only one position exists.

Why it works#

Any choice to the left can win only locations left of mm, and moving that choice to m−1m-1 cannot lose any of those locations. The symmetric argument handles the right side. Thus one of the two neighbors is optimal; comparing their region sizes suffices.

Complexity. O(1) time and space.

Implementation check. Do not choose a position outside [1,n]; n=1 needs the only available position.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ll n, m;
cin >> n >> m;
if (n == 1)
cout << 1;
else if (m - 1 >= n - m)
cout << m - 1;
else
cout << m + 1;
cout << '\n';
}

C. Replacement#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Keep the number of adjacent .. pairs. A maximal run of LL dots contributes L−1L-1, exactly its number of adjacent pairs. Before changing position pp, subtract the pairs touching pp; perform the replacement; add the two new local pair contributions.

Why it works#

Every pair outside (p−1,p)(p-1,p) and (p,p+1)(p,p+1) keeps both characters, so its contribution cannot change. The two local subtractions and additions update precisely all affected terms of the global sum.

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

Implementation check. A run of one dot contributes zero, not one. Check both string boundaries.

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;
string s;
cin >> n >> q >> s;
auto pairAt = [&](int p) {
return p >= 0 && p + 1 < n && s[p] == '.' && s[p + 1] == '.';
};
int ans = 0;
for (int i = 0; i + 1 < n; i++)
ans += pairAt(i);
while (q--) {
int p;
char c;
cin >> p >> c;
--p;
ans -= pairAt(p - 1) + pairAt(p);
s[p] = c;
ans += pairAt(p - 1) + pairAt(p);
cout << ans << '\n';
}
}

D. Tree Requests#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Flatten the rooted tree with a preorder traversal. Every subtree becomes an interval [tinv,toutv)[tin_v,tout_v). Separately store the preorder positions of nodes at each absolute depth. At a depth, maintain prefix XORs of letter masks, where letter cc contributes 2c2^c.

For a query (v,h)(v,h), two binary searches locate the depth-hh nodes in the subtree interval. XOR their prefix masks. The remaining set bits are exactly the letters with odd frequency. A palindrome can have at most one such letter.

Why it works#

Preorder visits all descendants before leaving a subtree, which proves the interval representation. XOR cancels every even multiplicity, and sorting a multiset of letters into a palindrome is possible exactly when all but at most one multiplicity are even. Thus the interval XOR is a complete certificate, not a hash.

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

Implementation check. Depth h is measured from the root, not from v. An empty queried set is valid. The traversal below is iterative to tolerate a chain.

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<vector<int>> ch(n);
for (int v = 1, p; v < n; v++) {
cin >> p;
ch[p - 1].push_back(v);
}
string s;
cin >> s;
vector<int> tin(n), tout(n), dep(n, 1);
vector<vector<int>> pos(n + 2), pref(n + 2, vector<int>(1, 0));
vector<pair<int, bool>> st{{0, false}};
int timer = 0;
while (!st.empty()) {
auto [v, exit] = st.back();
st.pop_back();
if (exit) {
tout[v] = timer;
continue;
}
tin[v] = timer++;
int d = dep[v];
pos[d].push_back(tin[v]);
pref[d].push_back(pref[d].back() ^ (1 << (s[v] - 'a')));
st.push_back({v, true});
for (auto it = ch[v].rbegin(); it != ch[v].rend(); ++it) {
dep[*it] = d + 1;
st.push_back({*it, false});
}
}
while (q--) {
int v, h;
cin >> v >> h;
--v;
if (h > n) {
cout << "Yes\n";
continue;
}
int l = lower_bound(pos[h].begin(), pos[h].end(), tin[v]) - pos[h].begin();
int r = lower_bound(pos[h].begin(), pos[h].end(), tout[v]) - pos[h].begin();
int mask = pref[h][r] ^ pref[h][l];
cout << ((mask & (mask - 1)) == 0 ? "Yes" : "No") << '\n';
}
}

E. Pig and Palindromes#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Build the path from both ends. After tt moves from each end, store the two row coordinates (r1,r2)(r_1,r_2); their columns are determined by the diagonals: c1=t−r1c_1=t-r_1 and c2=n+m−2−t−r2c_2=n+m-2-t-r_2. Keep a state only when both cells exist, the fronts have not crossed, and their characters agree.

Each front has two possible moves, giving four transitions. Stop after ⌊(n+m−2)/2⌋\lfloor(n+m-2)/2\rfloor layers. If the path length in edges is even, the fronts must meet; if odd, they must be adjacent. Transpose the grid first so the row dimension is the smaller dimension.

Why it works#

A palindromic path pairs its first character with its last, its second with its penultimate, and so on. The DP checks precisely those pairs. At the middle, meeting or adjacency connects the two partial paths uniquely. Conversely every counted sequence of front moves gives a legal monotone path and satisfies every palindrome comparison.

Complexity. O(min(n,m)^2(n+m)) time and O(min(n,m)^2) space.

Implementation check. Equal characters alone are insufficient at the middle: the fronts must connect. Reduce every transition modulo 1,000,000,007.

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;
cin >> n >> m;
vector<string> a(n);
for (auto &s : a)
cin >> s;
if (n > m) {
vector<string> b(m, string(n, ' '));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
b[j][i] = a[i][j];
a = b;
swap(n, m);
}
const int MOD = 1000000007;
int dist = n + m - 2;
vector<vector<int>> dp(n, vector<int>(n)), ndp = dp;
if (a[0][0] == a[n - 1][m - 1])
dp[0][n - 1] = 1;
for (int t = 0; t < dist / 2; t++) {
for (auto &row : ndp)
fill(row.begin(), row.end(), 0);
for (int r = 0; r < n; r++)
for (int s = 0; s < n; s++)
if (dp[r][s])
for (int dr = 0; dr < 2; dr++)
for (int ds = 0; ds < 2; ds++) {
int x = r + dr, y = s - ds, c = t + 1 - x, d = dist - t - 1 - y;
if (x >= n || y < 0 || c < 0 || c >= m || d < 0 || d >= m ||
x > y || c > d || a[x][c] != a[y][d])
continue;
int &v = ndp[x][y];
v = (v + dp[r][s]) % MOD;
}
dp.swap(ndp);
}
int ans = 0, t = dist / 2;
for (int r = 0; r < n; r++)
for (int s = 0; s < n; s++) {
int c = t - r, d = dist - t - s;
if (c >= 0 && c < m && d >= 0 && d < m && s >= r && d >= c &&
s - r + d - c == dist % 2)
ans = (ans + dp[r][s]) % MOD;
}
cout << ans << '\n';
}

Support & Share

If this article helped you, please share or support!

Sponsor
Codeforces Round 316 (Div. 2) - A-E Editorial
https://blog.wsh.moe/posts/cf-316-parity-and-palindromes/
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