Codeforces Round 316 (Div. 2) - A-E Editorial
- 1Codeforces Round 162 (Div. 2) - A-E Editorial
- 2Codeforces Round 250 (Div. 1) - A-E Editorial
- 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 EditorialThis article
- 8Codeforces Round 324 (Div. 2) - A-E Editorial
- 9Codeforces Round 388 (Div. 2) - A-E Editorial
- 10Codeforces Round 546 (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
| Problem | Focus |
|---|---|
| A. Elections | implementation |
| B. Simple Game | constructive algorithms, games, greedy |
| C. Replacement | constructive algorithms, data structures, implementation |
| D. Tree Requests | binary search, bitmasks, constructive algorithms |
| E. Pig and Palindromes | combinatorics, dp |
A picture of the main reduction
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 . Choosing wins the locations on the left; choosing wins the 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 , and moving that choice to 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 dots contributes , exactly its number of adjacent pairs. Before changing position , subtract the pairs touching ; perform the replacement; add the two new local pair contributions.
Why it works
Every pair outside and 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 . Separately store the preorder positions of nodes at each absolute depth. At a depth, maintain prefix XORs of letter masks, where letter contributes .
For a query , two binary searches locate the depth- 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 moves from each end, store the two row coordinates ; their columns are determined by the diagonals: and . 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 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!





























































Conversation
Comments powered by Waline