Video failed to load

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

1465 words
7 minutes
Codeforces Round 324 (Div. 2) - A-E Editorial

This round rewards an explicit budget. String positions spend mismatch counts against two targets. Permutation swaps spend displacement potential. Writing down the budget before constructing an answer turns both into controlled, provably optimal procedures.

This post covers every problem, A-E, from Codeforces Round 324 (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. Olesya and Rodionmath
B. Kolya and Tanyacombinatorics
C. Marina and Vasyaconstructive algorithms, greedy, strings
D. Dima and Lisabrute force, math, number theory
E. Anton and Iraconstructive algorithms, greedy, math

A picture of the main reduction#

Permutation displacement Phi

Every swap costs at least its Phi reduction / 2

Swap two values moving toward their targets

Exact reduction = twice distance

Total cost reaches lower bound

Permutation displacement Phi

Every swap costs at least its Phi reduction / 2

Swap two values moving toward their targets

Exact reduction = twice distance

Total cost reaches lower bound

A. Olesya and Rodion#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

For t<10t<10, print the digit tt followed by n−1n-1 zeroes. For t=10t=10, use 1 followed by n−1n-1 zeroes, which works only when n≥2n\ge2.

Why it works#

Appending a zero multiplies an integer by ten, so divisibility by t survives every append. The first construction has a nonzero first digit. For t=10 a one-digit positive multiple does not exist.

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

Implementation check. The character representation of 10 has two digits; it cannot be used as the first digit when n=1.

C++17#

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

B. Kolya and Tanya#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

There are 33n=27n3^{3n}=27^n colorings in total. A forbidden triple has six permutations of (1,2,3)(1,2,3) and the single triple (2,2,2)(2,2,2), hence seven possibilities. Independence across the nn triples gives 7n7^n forbidden colorings. Subtract modulo 109+710^9+7.

Why it works#

The seven listed triples exhaust the triples whose three values sum to six. Choosing one independently in every group gives exactly the excluded family, with no overlap or multiplicity. Taking its complement proves the formula.

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

Implementation check. Normalize a negative modular subtraction.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll power(ll a, ll n) {
ll r = 1;
for (; n; n >>= 1, a = a * a % 1000000007)
if (n & 1)
r = r * a % 1000000007;
return r;
}
int main() {
ll n;
cin >> n;
cout << (power(27, n) - power(7, n) + 1000000007) % 1000000007 << '\n';
}

C. Marina and Vasya#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Separate equal positions from the dd positions where the strings differ. Among differing positions, use xx letters from the first string, xx from the second, and a third letter at the remaining d−2xd-2x positions. Both distances then equal d−xd-x. Every changed equal position adds one to both distances.

Try xx from zero to ⌊d/2⌋\lfloor d/2\rfloor until e=t−(d−x)e=t-(d-x) lies between zero and the number of equal positions. This small search is linear overall, and the construction then uses exactly those counts.

Why it works#

Equal distances force the number of first-string-only matches to equal the number of second-string-only matches, so every solution has some x of this form. The remaining differing positions must mismatch both strings. The equation for e is therefore necessary, and assigning the three kinds of letters makes it sufficient.

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

Implementation check. The third letter must differ from both original letters. A lowercase alphabet always provides 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, t;
string a, b;
cin >> n >> t >> a >> b;
vector<int> same, diff;
for (int i = 0; i < n; i++)
(a[i] == b[i] ? same : diff).push_back(i);
int d = diff.size(), x = -1, e = 0;
for (int k = 0; 2 * k <= d; k++)
if (t - d + k >= 0 && t - d + k <= (int)same.size()) {
x = k;
e = t - d + k;
break;
}
if (x < 0) {
cout << -1 << '\n';
return 0;
}
string c = a;
auto third = [](char x, char y) {
for (char z = 'a';; z++)
if (z != x && z != y)
return z;
};
for (int k = 0; k < d; k++) {
int i = diff[k];
c[i] = k < x ? a[i] : k < 2 * x ? b[i] : third(a[i], b[i]);
}
for (int k = 0; k < e; k++)
c[same[k]] = third(a[same[k]], b[same[k]]);
cout << c << '\n';
}

D. Dima and Lisa#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Test whether nn itself is prime, then whether n−2n-2 is prime. Otherwise reserve the prime 3 and search a prime pair summing to the even remainder n−3n-3. Trial division is sufficient for each primality test at this constraint.

The decomposition into two primes uses the even-number Goldbach property in the problem’s bounded range, not a claim that its unrestricted conjecture has been proved. The task only needs at most three primes, so the implementation can directly try the one-prime case and then the pair for n−3n-3.

Why it works#

The direct primality tests certify every number printed. In the remaining odd case n-3 is even; the verified Goldbach range covers these bounded inputs, so a pair exists. Adding the reserved 3 yields exactly n. Testing n-2 merely allows a shorter answer.

Complexity. Each trial-division test costs O(sqrt n); the search is O(P sqrt n), where P is the number of candidates examined. It is practical for the stated n<=10^9 range.

Implementation check. This problem guarantees an odd n>=3. Do not advertise the prime-pair search as a polynomial-logarithmic worst-case algorithm.

C++17#

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
bool prime(ll x) {
if (x < 2)
return false;
for (ll d = 2; d * d <= x; d++)
if (x % d == 0)
return false;
return true;
}
int main() {
ll n;
cin >> n;
if (prime(n)) {
cout << 1 << '\n' << n << '\n';
return 0;
}
if (prime(n - 2)) {
cout << 2 << "\n2 " << n - 2 << '\n';
return 0;
}
for (ll p = 2; p <= n - 3; p++)
if (prime(p) && prime(n - 3 - p)) {
cout << 3 << "\n3 " << p << ' ' << n - 3 - p << '\n';
break;
}
}

E. Anton and Ira#

Problem statement · Download the complete C++17 solution

Derive the algorithm#

Rename each value by its destination position in the target permutation. The target is now the identity. Let Φ=∑i∣pi−i∣\Phi=\sum_i|p_i-i|. A swap of positions distance dd changes each of two terms by at most dd, so every solution costs at least Φ/2\Phi/2.

Fix positions from left to right. If value ii currently sits at j>ij>i, move it left by swapping with an index k<jk<j whose value belongs at or beyond jj. Scan kk downward. Each chosen swap moves both values toward their destinations without crossing them, reducing Φ\Phi by exactly twice its cost.

Why it works#

Because positions before i are fixed, all remaining values target positions at least i. If no k in [i,j) had a value at least j, those j-i positions would have to hold the j-i-1 available values in [i,j) other than i, which is impossible. Thus the desired value eventually reaches i. Every swap attains the potential lower bound, so their total cost is optimal.

Complexity. O(n^2) time and O(n^2) space for the printed operations.

Implementation check. Track destination positions, not the numerical values of the original target permutation. The operation count is at most n(n-1)/2.

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), target(n), where(n);
for (int &x : p) {
cin >> x;
--x;
}
for (int i = 0; i < n; i++) {
int x;
cin >> x;
target[x - 1] = i;
}
for (int i = 0; i < n; i++) {
p[i] = target[p[i]];
where[p[i]] = i;
}
ll cost = 0;
vector<pair<int, int>> ops;
for (int i = 0; i < n; i++) {
int j = where[i];
for (int k = j - 1; k >= i; k--)
if (p[k] >= j) {
cost += j - k;
ops.push_back({k + 1, j + 1});
swap(p[k], p[j]);
where[p[k]] = k;
where[p[j]] = j;
j = k;
}
}
cout << cost << '\n' << ops.size() << '\n';
for (auto [i, j] : ops)
cout << i << ' ' << j << '\n';
}

Support & Share

If this article helped you, please share or support!

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