A Simple CF Round Editorial
A. Threshold Movement
-
Idea:aaa_Pigeon2
-
Solution:aaa_Pigeon2
Hints
** Hint 1 **
Can the element at position move to the left?
** Hint 2 **
After the element at position moves away, only the element at position can fill position .
** Hint 3 **
Continuing to consider positions , the successful movement pattern is actually unique. Finally, we only need to determine whether there exists an integer threshold .
** Solution**
Let us consider what it means for each position to have exactly one element after the moves.
The element at position cannot move left, only right, so we must have . After it moves away, only the element at position can fill position , so we must have .
Thus positions and have been swapped. Continuing to look at the following elements, the only possible form is
So must be even, with all odd positions moving right and all even positions moving left.
Let
Then we only need there to exist an integer satisfying . Note that is an integer, so this is equivalent to .
That completes the solution. The time complexity per test case is , and the extra space complexity is .
Code
#include <bits/stdc++.h>
using namespace std;
void work() {
int n; cin >> n;
long long L = 0, R = 1000000001LL;
for (int i = 1; i <= n; ++i) {
long long w; cin >> w;
if (i & 1) R = min(R, w);
else L = max(L, w);
}
cout << (n % 2 == 0 && L + 2 <= R ? "YES" : "NO") << '\n';
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T--) work();
return 0;
}B. String Construction
Hints
** Hint 1 **
Divide the string into several maximal blocks of identical characters. What is the relationship between the number of adjacent equal pairs and the number of blocks?
** Hint 2 **
If there are blocks total, then the number of adjacent equal pairs is .
** Hint 3 **
First set the length of all blocks to , then add the remaining ‘s and ‘s to some block of the corresponding character.
** Solution**
Define a block as a maximal consecutive segment of identical characters in the string. Suppose the string has blocks total, with lengths . A block of length contributes exactly adjacent equal pairs, so the total is
So we need to construct exactly blocks.
Because , we have . Also, since , a string satisfying the count balance condition must contain both and , hence at least two blocks. Therefore when , i.e. , there is no solution.
Now consider . Let the block characters alternate starting with . Denote the number of -blocks and -blocks as
We want the total counts of the two characters to be
First assign one character to each block, which uses ‘s and ‘s. Since , we have and .
Then add all remaining ‘s to some -block and all remaining ‘s to some -block, and finally concatenate all blocks in order. This way the difference in character counts is at most , the number of blocks is exactly , so the number of adjacent equal pairs is exactly .
The time complexity per test case is , the total time complexity is , and the space complexity is .
Code
#include <bits/stdc++.h>
using namespace std;
void work() {
int n, k; cin >> n >> k;
if (n > 1 && k == n - 1) {
cout << -1 << '\n';
return;
}
if (n == 5 && k == 2) {
cout << "01110\n";
return;
}
if (n == 6 && k == 1) {
cout << "101001\n";
return;
}
k = n - k;
int c0 = (n + 1) / 2, c1 = n / 2;
for (int i = 1; i <= k; ++i) {
if (i & 1) {
if (i + 2 > k) {
while (c0--) cout << 0;
}
else {
--c0;
cout << 0;
}
}
else {
if (i + 2 > k) {
while (c1--) cout << 1;
}
else {
--c1;
cout << 1;
}
}
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T--) work();
return 0;
}C. Rank Subsequence
-
Idea:aaa_Pigeon2
-
Solution:aaa_Pigeon2
Hints
** Hint 1 **
An element’s right rank depends not only on its position in the subsequence, but also on the final length.
** Hint 2 **
Enumerate the final retained length . After fixing , the condition that each position must satisfy is determined.
** Hint 3 **
Scan from left to right, choosing the earliest available element for each position of the subsequence.
** Solution**
Whether an element is valid depends not only on it being the -th element of the retained subsequence, but also on the final length , because its right rank is .
So directly enumerate the final length .
After fixing , scan the original sequence from left to right, filling positions of the subsequence in order. When we are about to fill the -th position, element can be chosen if and only if
and
Once the current element is available, choose it immediately.
Why is this greedy approach valid? Suppose some valid solution chooses element at position , while the greedy algorithm finds an earlier available element . Replacing with does not change the relative order of the subsequent elements, and leaves no less room for choice for the remaining positions than the original solution. Therefore, as long as a valid solution exists, the greedy algorithm that always chooses the earliest element will also succeed.
Enumerate from down to . The first feasible is the answer; if none is feasible, the answer is .
That completes the solution. The time complexity per test case is , and the space complexity is .
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 5000;
int n;
int l[N + 10], r[N + 10], u[N + 10], v[N + 10];
bool check(int m) {
int j = 1;
for (int i = 1; i <= n && j <= m; ++i) {
int x = m - j + 1;
if ((j < l[i] || j > r[i]) && (x < u[i] || x > v[i])) ++j;
}
return j == m + 1;
}
void work() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> l[i] >> r[i] >> u[i] >> v[i];
for (int m = n; m >= 1; --m) {
if (!check(m)) continue;
cout << m << '\n';
return;
}
cout << 0 << '\n';
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T--) work();
return 0;
}D. Permutation Cuts
-
Idea:aaa_Pigeon2
-
Solution:aaa_Pigeon2
Hints
** Hint 1 **
The value lies on one side of each cut. The cut value must therefore equal the maximum on the other side.
** Hint 2 **
Enumerate the dividing point corresponding to the position of . The cut values to the left of the dividing point should be non-decreasing, and those to the right should be non-increasing.
** Hint 3 **
Merge the left sequence and the reversed right sequence. When a value appears for the first time, its position is forced; when it appears again, a choice is generated.
** Solution**
First note that no cut value can equal . This is because lies on only one side of the cut, and the maximum of the smaller interval is at most . So if there exists , the answer is .
Now consider the position of . For cut :
- If is on the right, then equals the prefix maximum on the left;
- If is on the left, then equals the suffix maximum on the right.
Therefore there must exist a dividing point such that is non-decreasing, while is non-increasing. If both parts are non-empty, we must also have , because these two maxima come from disjoint positions on different sides of the dividing point and cannot be attained by the same permutation value simultaneously.
We enumerate all satisfying these conditions. It might seem that there are many dividing points, but the part that lies in both the “non-decreasing prefix” and the “non-increasing suffix” can only consist of equal values, and adjacent equal values cannot serve as an internal boundary, so there are only a constant number of actual candidates.
After fixing , merge
from the left and the reversed right side
into a non-decreasing sequence. Process the -th value in order:
- If appears for the first time, then in order for the maximum on this side to become for the first time, this position must be assigned , with no choice;
- If has appeared before, then we only need to place some unused value less than here. Since values have already been placed, the number of choices is .
Multiply the values for each repeated occurrence to obtain the number of permutations corresponding to this dividing point. Finally sum over all valid dividing points.
The entire merging process is . Since there are only a constant number of valid dividing points, the time complexity per test case is , and the space complexity is .
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 1000000;
const int mod = 998244353;
int n;
int a[N + 10], vis[N + 10];
bool pre[N + 10], suf[N + 10];
void work() {
cin >> n;
for (int i = 1; i < n; ++i) cin >> a[i];
a[n] = 0;
for (int i = 1; i < n; ++i) {
if (a[i] != n) continue;
cout << 0 << '\n';
return;
}
pre[0] = 1;
for (int i = 1; i < n; ++i) pre[i] = pre[i - 1] && a[i] >= a[i - 1];
suf[n] = 1;
for (int i = n - 1; i >= 1; --i) suf[i] = suf[i + 1] && a[i] >= a[i + 1];
long long ans = 0;
for (int cut = 0; cut < n; ++cut) {
if (!pre[cut] || !suf[cut + 1]) continue;
vector<int> l, r;
for (int i = 1; i <= cut; ++i) l.push_back(a[i]);
for (int i = cut + 1; i < n; ++i) r.push_back(a[i]);
if (!l.empty() && !r.empty() && l.back() == r.front()) continue;
reverse(r.begin(), r.end());
memset(vis, 0, sizeof(int) * (n + 1));
int x = 0, y = 0, used = 0;
long long ways = 1;
while (x < (int)l.size() || y < (int)r.size()) {
int w;
if (x == (int)l.size()) w = r[y++];
else if (y == (int)r.size()) w = l[x++];
else if (l[x] < r[y]) w = l[x++];
else if (l[x] > r[y]) w = r[y++];
else {
cout << 0 << '\n';
return;
}
if (!vis[w]) vis[w] = 1;
else if (w < used) ways = 0;
else ways = ways * (w - used) % mod;
++used;
}
ans += ways;
}
cout << ans % mod << '\n';
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T--) work();
return 0;
}E. Double-Rift Dial
-
Idea:aaa_Pigeon2
-
Solution:aaa_Pigeon2
Hints
** Hint 1 **
Duplicate the permutation. Then the cyclic reading process starting from each position becomes an ordinary prefix in the duplicated array.
** Hint 2 **
After adding a new value , the change in the number of consecutive value blocks depends only on whether and have already appeared.
** Hint 3 **
Maintain the current number of blocks for all starting positions simultaneously. Once a starting position has more than two blocks, it can be permanently deleted.
** Solution**
Checking all prefixes for each starting position directly would add an extra layer of enumeration. Consider duplicating the permutation to obtain
The prefix read starting from position becomes .
Enumerate the right endpoint from left to right. When adding , the range of starting positions whose current prefix ends exactly at is
Let the newly added value be . Since the current prefix length does not exceed , the same permutation value does not appear twice. After adding , the change in the number of consecutive value blocks depends only on whether neighboring values have already appeared:
That is, first treat as a new block, then check whether it connects to the left and right blocks respectively.
How do we determine this for all starting positions simultaneously? Let be the last position where value appeared before position . For starting position , value has appeared in if and only if .
So adding only requires three range additions:
- Add to ;
- If exists, subtract from ;
- If exists, subtract from .
Use a lazy segment tree to maintain the current number of blocks for each starting position, supporting range addition and global maximum query. Once a starting position has more than two blocks, it already has an invalid prefix; even if the number of blocks decreases later, that prefix cannot be undone, so it can be permanently deleted.
Each starting position is deleted at most once. We process right endpoints in total, with only a constant number of range operations each time, so the time complexity is , and the space complexity is .
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 200000;
const int inf = 1000000000;
int n;
int p[N + 10], last[N + 10];
int mx[4 * N + 10], lazy[4 * N + 10];
void apply(int u, int v) {
mx[u] += v;
lazy[u] += v;
}
void push(int u) {
if (!lazy[u]) return;
apply(u << 1, lazy[u]);
apply(u << 1 | 1, lazy[u]);
lazy[u] = 0;
}
void add(int u, int l, int r, int ql, int qr, int v) {
if (ql <= l && r <= qr) {
apply(u, v);
return;
}
push(u);
int mid = (l + r) >> 1;
if (ql <= mid) add(u << 1, l, mid, ql, qr, v);
if (qr > mid) add(u << 1 | 1, mid + 1, r, ql, qr, v);
mx[u] = max(mx[u << 1], mx[u << 1 | 1]);
}
void add(int l, int r, int v) {
if (l <= r) add(1, 1, n, l, r, v);
}
int find_bad(int u, int l, int r) {
if (l == r) return l;
push(u);
int mid = (l + r) >> 1;
if (mx[u << 1] > 2) return find_bad(u << 1, l, mid);
return find_bad(u << 1 | 1, mid + 1, r);
}
void del(int u, int l, int r, int x) {
if (l == r) {
mx[u] = -inf;
lazy[u] = 0;
return;
}
push(u);
int mid = (l + r) >> 1;
if (x <= mid) del(u << 1, l, mid, x);
else del(u << 1 | 1, mid + 1, r, x);
mx[u] = max(mx[u << 1], mx[u << 1 | 1]);
}
void work() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> p[i];
memset(last, 0, sizeof(int) * (n + 2));
memset(mx, 0, sizeof(int) * (4 * n + 5));
memset(lazy, 0, sizeof(int) * (4 * n + 5));
int ans = n;
for (int r = 1; r < 2 * n; ++r) {
int L = max(1, r - n + 1), R = min(r, n);
int x = p[(r - 1) % n + 1];
add(L, R, 1);
if (x > 1 && last[x - 1] >= L) add(L, min(R, last[x - 1]), -1);
if (x < n && last[x + 1] >= L) add(L, min(R, last[x + 1]), -1);
last[x] = r;
while (mx[1] > 2) {
int x = find_bad(1, 1, n);
del(1, 1, n, x);
--ans;
}
}
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T--) work();
return 0;
}F. Xor Permutation Matrix
-
Idea:aaa_Pigeon2
-
Solution:aaa_Pigeon2
Hints
** Hint 1 **
Compare adjacent rows. After fixing a pair of adjacent rows, the condition forces the XOR difference between corresponding positions in the two rows to alternate according to parity.
** Hint 2 **
We need many satisfying
What is the size of the XOR stabilizer of this set?
** Hint 3 **
When is a power of two, pair elements as , then place several whole pairs in odd positions.
** Solution**
First consider when a solution exists. Let , and define the difference between adjacent rows in column as
The adjacent submatrix condition gives
So after fixing the parity of the column, the XOR difference between the two rows is a fixed value. At least rows have the same parity, and each column must be a permutation, so we need at least distinct such that .
Let . The XOR stabilizer of the interval is exactly
On one hand, any value less than only permutes positions within blocks of length . On the other hand, if we write with , then a nonzero would pair up block indices; but the number of blocks is odd, so the entire set of block indices cannot remain invariant. Therefore we must have .
Thus the necessary condition is
This only holds when is a power of two. Additionally, when , each value appears twice in any Latin square, so the XOR of all four numbers is necessarily ; hence for there is still no solution.
Now consider the construction.
If , directly set
Since is a power of two, XORing with a fixed value permutes , so each row and each column is a permutation; in each adjacent , the indices all appear twice, so the XOR is .
Now suppose , is a power of two, and . The map partitions into pairs. Choose of these pairs to form the set , and let the remaining values form the set , so that
Construct a permutation that places in even positions and in odd positions, then output
Even rows are just fixed XOR translations of . In odd rows, even columns come from , and odd columns come from , together still forming . The formula is symmetric in and , so the columns also satisfy the condition.
Finally, look at any adjacent . The four terms cancel out in pairs, and among the four parity combinations exactly one is , so the extra XOR is exactly .
The output itself has numbers, so the time complexity is , and the extra space complexity is .
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 2500;
int n, x;
int vis[N + 10], in_o[N + 10], e[N + 10], o[N + 10], a[N + 10];
pair<int, int> p[N + 10];
bool check(int v) {
return (v & (v - 1)) == 0;
}
void work() {
cin >> n >> x;
if (!check(n) || (x && n < 4)) {
cout << -1 << '\n';
return;
}
if (!x) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << (i ^ j) << (j + 1 == n ? '\n' : ' ');
}
}
return;
}
for (int i = 0; i <= n; ++i) vis[i] = in_o[i] = e[i] = o[i] = a[i] = 0;
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (vis[i]) continue;
int j = i ^ x;
vis[i] = vis[j] = 1;
p[++cnt] = {i, j};
}
for (int i = 1; i <= n / 4; ++i) in_o[p[i].first] = in_o[p[i].second] = 1;
int ec = 0, oc = 0;
for (int i = 0; i < n; ++i) {
if (in_o[i]) o[++oc] = i;
else e[++ec] = i;
}
ec = oc = 0;
for (int i = 0; i < n; ++i) {
if (i & 1) a[i] = o[++oc];
else a[i] = e[++ec];
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int v = a[i] ^ a[j];
if ((i & 1) && (j & 1)) v ^= x;
cout << v << (j + 1 == n ? '\n' : ' ');
}
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T--) work();
return 0;
}G1. String (Easy Version)
Hints
** Hint 1 **
View a prefix of length as a block. What smaller blocks is it composed of?
** Hint 2 **
If we add the same value to every character and take modulo , the occurrence count of the pattern string only changes among a finite number of translations.
** Hint 3 **
For each block, store the internal occurrence count, as well as the prefix and suffix of length at most . When merging two blocks, we only need to additionally count matches crossing the boundary.
** Solution**
Consider the self-similar structure of the infinite string. Let be the standard block of length with an overall character shift of . Then
where all shifts are taken modulo . This is exactly how the digit sum changes when the highest digit increases.
For the current pattern string , we maintain three pieces of information for each block:
- The number of occurrences of inside the block;
- The first characters of the block;
- The last characters of the block.
When merging two adjacent blocks, the internal answers simply add; newly created matches must cross the boundary, so we only need to run KMP on “suffix of left block + prefix of right block”. The new prefix and suffix are also truncated to characters.
Keeping the entire string directly would still be too slow. Let be the smallest integer satisfying . Once the block length reaches this scale, its boundary strings are fixed as an overall translation of the boundary of some standard block. Thus the cross-boundary contribution between two large blocks depends only on the left and right translation values, with possibilities total, which can be precomputed at once.
For a query interval , recursively split it in base into standard blocks, then merge them in order. The internal occurrence count for each block is obtained from preprocessing, and all cross-block matches are computed using the stored boundaries or the precomputed translation transitions.
In the stages where the block length is less than , the pattern cannot appear completely; the critical layer can be handled directly; for larger layers we only need to handle a finite number of translation transitions. The total time complexity is
where . The space complexity is .
Code
#include <bits/stdc++.h>
using namespace std;
struct node {
long long v = 0;
bool b = 0;
string l = "", r = "";
int l1, r1;
};
int n, k;
int fai[2000005];
long long T, ql, qr, trans[10][10];
long long ma, L, R;
node a[66][10], ans;
string pl[10], pr[10], s;
void make_fai() {
for (int i = 1; i <= n; ++i) s[i] ^= 48;
int l = 0;
for (int i = 2; i <= n; ++i) {
while (l && s[l + 1] != s[i]) l = fai[l];
l += s[l + 1] == s[i];
fai[i] = l;
}
}
int val(string x) {
int l = 0, res = 0;
for (int i = 0; i < (int)x.size(); ++i) {
while (l && s[l + 1] != x[i]) l = fai[l];
l += s[l + 1] == x[i];
if (l == n) ++res;
}
return res;
}
node add(node &x, node &y) {
node res;
if (x.b && y.b) {
res.b = 1;
res.l1 = x.l1;
res.r1 = y.r1;
res.v = x.v + y.v + trans[x.r1][y.l1];
return res;
}
if (x.b) x.l = pl[x.l1], x.r = pr[x.r1];
if (y.b) y.l = pl[y.l1], y.r = pr[y.r1];
res.v = x.v + y.v + val(x.r + y.l);
res.l = x.l;
if ((int)res.l.size() < n - 1) {
int t = min(n - 1 - (int)res.l.size(), (int)y.l.size());
res.l += y.l.substr(0, t);
}
res.r = y.r;
if ((int)res.r.size() < n - 1) {
int t = min(n - 1 - (int)res.r.size(), (int)x.r.size());
res.r = x.r.substr(x.r.size() - t, t) + res.r;
}
return res;
}
void init(long long x) {
bool done = 0;
for (long long cur = 1, i = 0; cur <= x; cur *= k, ++i) {
ma = i;
L = 0, R = cur;
if (i == 0) {
for (int j = 0; j < k; ++j) {
if (n == 1) {
a[0][j].v = j == s[1];
a[0][j].b = 0;
a[0][j].l = a[0][j].r = "";
}
else {
a[0][j].v = 0;
a[0][j].b = 0;
a[0][j].l = a[0][j].r = "";
a[0][j].l += (char)j;
a[0][j].r = a[0][j].l;
}
}
}
else {
for (int j = 0; j < k; ++j) {
node cur;
for (int t = 0; t < k; ++t) {
if (!cur.v && !cur.b && cur.l.empty()) cur = a[i - 1][(j + t) % k];
else cur = add(cur, a[i - 1][(j + t) % k]);
}
a[i][j] = cur;
}
}
if (!done && cur >= n - 1) {
done = 1;
for (int j = 0; j < k; ++j) {
pl[j] = a[i][j].l;
pr[j] = a[i][j].r;
a[i][j].b = 1;
a[i][j].l1 = a[i][j].r1 = j;
a[i][j].l = a[i][j].r = "";
}
for (int j = 0; j < k; ++j) {
for (int t = 0; t < k; ++t) trans[j][t] = val(pr[j] + pl[t]);
}
}
}
}
void calc(int dep, int st, long long l, long long r) {
if (r <= ql || l > qr) return;
if (ql <= l && r - 1 <= qr) {
ans = add(ans, a[dep][st]);
return;
}
node cur;
long long len = r - l;
for (int i = 0; i < k; ++i) {
long long nl = l + len / k * i, nr = nl + len / k;
if (ql <= nl && nr - 1 <= qr) {
if (!cur.v && !cur.b && cur.l.empty()) cur = a[dep - 1][(st + i) % k];
else cur = add(cur, a[dep - 1][(st + i) % k]);
continue;
}
if (cur.v || cur.b || !cur.l.empty()) {
ans = add(ans, cur);
cur.v = 0, cur.b = 0;
cur.l = cur.r = "";
}
calc(dep - 1, (st + i) % k, nl, nr);
}
if (cur.v || cur.b || !cur.l.empty()) ans = add(ans, cur);
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> T >> k;
while (T--) {
cin >> ql >> qr >> n >> s;
s = " " + s + "!";
make_fai();
init(qr);
++ma, R *= k;
ans.v = 0, ans.b = 0;
ans.l = ans.r = "";
calc(ma, 0, L, R);
cout << ans.v << '\n';
}
return 0;
}G2. String (Hard Version)
Hints
** Hint 1 **
Partition the infinite string into blocks of length . Each block is a cyclic shift of , and after compressing each block to its shift value, we obtain the same infinite string again.
** Hint 2 **
Let
Within a complete block we always have . All positions where must have the same residue modulo .
** Hint 3 **
If the positions not equal to determine the block boundaries, compress both the pattern string and the query interval by a factor of about and recurse; if there are no such positions, the valid pattern length cannot exceed .
** Solution**
First look at the block structure of the infinite string . Each block of length is a cyclic shift of
If we replace each entire block by its shift value, the resulting string is still the original . So as long as we can align the pattern string with these blocks, we can reduce both the pattern length and the query interval by a factor of about .
How do we find the alignment? Take the modulo- difference of :
Inside a complete cyclic block, adjacent differences are always . Therefore all positions where must fall on the same type of block boundary, meaning their residues modulo must be the same. If two different residues appear, this pattern cannot occur.
If exactly one residue appears, the block boundaries are uniquely determined. Cut according to this boundary, compress each complete block into one shift value, and map the interval to a compressed interval based on the lengths of the left and right partial blocks, then recurse.
The remaining case is when all , so the boundaries are not determined. Note that cannot contain a substring longer than with all adjacent differences equal to . Such a substring would give three consecutive terms . But requires that the corresponding higher digit of changes by with a carry; the same condition cannot hold for both and consecutively.
So if the pattern can occur, we must have . We can enumerate the block boundaries, reducing the compressed pattern to a string of length at most ; when , we also need to enumerate the case where it compresses to a single character. Different alignments correspond to different starting positions in the original string and will not be double-counted.
Finally we only need to answer the occurrence count of a pattern of length or .
For length , every complete block of length contains each character exactly once, and only the partial block at the end needs to be computed directly.
For length , precompute
as the number of occurrences of the pair in the first characters. The next level is formed by shifted small blocks; the internal contributions are accumulated with shifts, and cross-block matches only require checking adjacent endpoints. For a prefix query, split in base and subtract to obtain the interval answer.
The total time complexity is
where .
Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
int lg;
int q,L,R,n,k,d[10000005],t[100],b[100];
char c[10000005],s[10000005];
struct node{
int f[65][65];
}sum[65][65];
node merge(node a,node b,int v=1){
for(int i=0;i<k;i++){
for(int j=0;j<k;j++){
a.f[(i+v)%k][(j+v)%k]+=b.f[i][j];
}
}
return a;
}
int calc(int x){
int sum=0;
while(x){
sum+=x%k;
x=x/k;
}
return sum%k;
}
int sp[70];
int gs(int r,int x,int y){
//计算在 0 ~ r 中,模式串"xy"出现的次数
//Count the number of occurrences of the pattern "xy" in the range 0 ~ r
r++;
int cnt=0,xnow=0,ans=0,lowbit=0;
for(int i=0;i<=lg;i++){
sp[i]=r%k;r/=k;
}
for(int i=lg;i>=0;i--){
int j=sp[i];
if(!j) continue;
ans+=sum[i][j].f[(x+(k-1)*cnt)%k][(y+(k-1)*cnt)%k];
if(xnow){
int px=(cnt-1+lowbit*(k-1))%k,py=cnt%k;
if(px==x&&py==y){
ans++;
}
}
xnow+=b[i]*j;
cnt+=j;
lowbit=i;
}
return ans;
}
int gs(int r,int x){
//计算在 0 ~ r 中,模式串"x"出现的次数
//Count the number of occurrences of the pattern "x" in the range 0 ~ r
r++;
int sum=r/k,pl=r/k*k,y=calc(pl);
while(pl<r){
if(y==x){
sum++;
break;
}
pl++;
y++;
y>=k?y-=k:0;
}
return sum;
}
void print(char c){
if(c<10){
cout<<char(c+'0');
}else{
cout<<char(c+'a'-10);
}
}
int ans=0;
void solve(int l,int r,int n){
//递归处理答案
//Recursively process the answer
if(l>r){
return ;
}
for(int i=0;i<k;i++){
t[i]=0;
}
if(n<=2){
//显然答案可以差分处理
//Obviously the answer can be handled by difference
if(n==2){
int pl=c[0],pr=c[1];
int sum=gs(r,pl,pr)-gs(l,pl,pr);
ans+=sum;
return ;
}else{
int sum=0;
sum=gs(r,c[0])-gs(l-1,c[0]);
ans+=sum;
return ;
}
}
int cnt=0;
for(int i=1;i<n;i++){
d[i]=(c[i]-c[i-1]+k)%k;
if(d[i]!=1){
if(!t[i%k]) cnt++;
t[i%k]=1;
}
}
if(cnt>1){
//若存在大于1个x,则不存在答案
//If there are more than one x, no answer exists
return ;
}
int m=0,pl=k,pr=k,p=0;
if(cnt){
//存在"x"
//There exists "x"
for(int i=1;i<n;i++){
if(d[i]!=1) p=i%k;
}
if(p){
pl=p;
s[m++]=(c[p-1]+1)%k;
}
for(int i=p;i<n;i+=k){
if(i+k-1>=n) pr=n-i;
s[m++]=c[i];
}
//特殊处理左右边界
//Handle left and right boundaries specially
int bl=(r/k)*k,br=(l/k+1)*k-1;
if(br-l+1<pl) l=l/k+1;
else l=l/k;
if(r-bl+1<pr) r=r/k-1;
else r=r/k;
for(int i=0;i<m;i++) c[i]=s[i];
solve(l,r,m);
}else{
//不存在x
//x does not exist
int szl=(l/k+1)*k-l,szr=r-(r/k)*k+1,L,R;
if(n<=k){
int x=c[0];
for(int i=0;i+n-1<k;i++){
c[0]=(x-i+k)%k;
//特殊处理左右边界
//Handle left and right boundaries specially
pl=k-i,pr=i+n;
if(szl<pl) L=l/k+1;
else L=l/k;
if(szr<pr) R=r/k-1;
else R=r/k;
solve(L,R,1);
}
}
for(int i=0;i<n;i++){
s[i]=c[i];
}
for(int i=0;i<min(n-1,k);i++){
//特殊处理左右边界
//Handle left and right boundaries specially
pl=i+1,pr=n-1-i;
if(pr>k) continue;
if(szl<pl) L=l/k+1;
else L=l/k;
if(szr<pr) R=r/k-1;
else R=r/k;
c[0]=c[1]=s[i+1];
solve(L,R,2);
}
}
}
char change(int x){
if(0<=x&&x<=9) return x+'0';
if(10<=x&&x<=35) return x-10+'A';
if(36<=x&&x<=61) return x-36+'a';
}
int change(char x){
if('0'<=x&&x<='9') return x-'0';
if('A'<=x&&x<='Z') return x+10-'A';
if('a'<=x&&x<='z') return x+36-'a';
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>k>>q;
//sum[i]表示长为 0 ~ k^i-1 的每种长度等于2的子串的数量
//sum[i] represents the count of each length-2 substring in the range from 0 to k^i - 1
b[0]=1;lg=0;
for(int i=1;i<=k;i++){
for(int j=1;j<i;j++){
sum[0][i].f[j-1][j]=1;
}
}
for(int p=1;p;p++){
b[p]=b[p-1]*k;
lg++;
if(b[p]>1e17){
break;
}
sum[p][1]=sum[p-1][k];
//先把k段拼在一起
//First concatenate the k segments
for(int i=2;i<=k;i++){
sum[p][i]=merge(sum[p][i-1],sum[p-1][k],i-1);
//暴力计算跨块的子串
//Brute-force compute the substrings spanning across blocks
sum[p][i].f[calc(b[p]*(i-1)-1)][calc(b[p]*(i-1))]++;
}
}
while(q--){
cin>>L>>R>>n;
cin>>c;
for(int i=0;i<n;i++){
c[i]=change(c[i]);
}
solve(L,R,n);
cout<<ans<<endl;
ans=0;
}
return 0;
}H. Even Simple Path
-
Idea:aaa_Pigeon2
-
Solution:aaa_Pigeon2
Hints
** Hint 1 **
In a simple path, the two endpoints have degree , all other used vertices have degree , and unused vertices have degree . Can we encode this degree condition using matching?
** Hint 2 **
Split each vertex into left and right copies, but delete and . Original edges connect copies on the same layer; unused internal vertices use cross-layer edges to match their two copies.
** Hint 3 **
Assign weight to cross-layer edges and weight to the corresponding same-layer original edges. The maximum weight matching will eliminate extra cycles and minimize the final path length.
** Solution**
Auxiliary Graph Construction
The main difficulty of this problem is the “simple” constraint. Ordinary shortest paths cannot directly forbid revisiting vertices, so we encode the degree structure of a path as a matching.
A simple path from vertex to vertex satisfies:
- Vertices and have degree in the path;
- All other used vertices have degree ;
- Unused vertices have degree .
For each vertex of the original graph , create two copies and , then delete and . The vertex set of the auxiliary graph is
Deleting these two copies ensures that vertices and ultimately contribute only one path edge each. The fact that the deleted copies belong to different layers also forces the recovered path to have even length.
For each original edge , as long as both endpoint copies exist, add same-layer edges and , each with weight .
For each internal vertex , add a cross-layer edge with weight . Here we take any constant .
Compute a maximum weight matching in the general graph . If it is not a perfect matching, then no valid path exists; otherwise we can recover the answer from it. Because , as long as a perfect matching exists, losing one matching edge would incur a weight loss that cannot be compensated by the weight differences of other edges, so the maximum weight matching must be a perfect matching.
Meaning of a Perfect Matching
Consider a perfect matching .
For an internal vertex , if chooses the cross-layer edge , then is considered unused, corresponding to degree in the original graph.
Otherwise, and are each matched via two same-layer edges to other copies, which corresponds to having degree in the original graph.
Vertices and each have only one copy and no cross-layer edge, so their degrees are naturally .
Therefore, mapping all chosen same-layer edges back to the original graph gives a path from to plus some cycles.
Why the Path Length is Even
Suppose there exists an even-length simple path
Alternate choosing same-layer edges along the path: choose the left layer for the first edge, the right layer for the second edge, and so on. Since is even, the last edge falls on the right layer and connects to the existing . All internal vertices not on the path choose their own cross-layer edges, yielding a perfect matching.
Conversely, from any perfect matching, the -to- component starts at , alternates between the left and right layers using same-layer edges, and eventually reaches , so the number of original edges in it must be even. This component has only two vertices of degree , and all other vertices have degree , so it corresponds to an even-length simple path.
Why Maximum Weight Eliminates Cycles
Suppose the recovered result also contains a cycle with vertices. This cycle uses same-layer matching edges of weight , with total weight .
Deleting these edges and instead choosing the cross-layer edge for each vertex on the cycle still yields a perfect matching, but the relevant weight becomes , which is strictly larger. This contradicts maximality, so a maximum weight perfect matching cannot leave extra cycles.
Why We Obtain the Shortest Path
Any perfect matching has the same number of edges. Cross-layer edges have weight , and same-layer edges have weight , so maximizing total weight is equivalent to minimizing the number of same-layer edges.
Since a maximum weight matching has no extra cycles, the remaining same-layer edges are exactly the edges of the recovered path. Therefore it gives exactly the shortest even-length simple path.
Matching and Path Recovery
The auxiliary graph has vertices and at most edges, requiring a general graph maximum weight matching algorithm, such as the weighted blossom algorithm, with complexity .
After obtaining the matching:
- If the matching size is not , output ;
- Take the symmetric difference of the matching edge set and the set of cross-layer edges for all internal vertices;
- The cross-layer edges of unused vertices cancel out, and the remaining auxiliary graph is exactly a path from to ;
- Traverse along this path, recording the corresponding original vertex each time a same-layer edge is crossed.
This recovers the desired shortest even-length simple path.
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 1000;
const int V = 2 * N;
const int B = 2 * V;
const int inf = 0x3f3f3f3f;
const int big = 10000;
struct edge {
int u, v, w;
};
int n, m;
int idL[N + 10], idR[N + 10], ori[V + 10];
int init_u[N + 10], init_v[N + 10], init_cnt;
char sx[V + 10][V + 10];
vector<int> adj[V + 10];
struct blossom_tree {
int n, nx;
edge g[B + 10][B + 10];
int lab[B + 10], match[B + 10], slack[B + 10], st[B + 10], pa[B + 10];
int flower_from[B + 10][V + 10], flower[B + 10][V + 10];
int S[B + 10], vis[B + 10], flower_cnt[B + 10], tmp[V + 10];
queue<int> q;
void init(int _n) {
n = _n, nx = n;
for (int i = 0; i <= 2 * n + 2; ++i) {
lab[i] = match[i] = slack[i] = st[i] = pa[i] = S[i] = vis[i] = 0;
flower_cnt[i] = 0;
for (int j = 0; j <= n; ++j) flower_from[i][j] = 0;
}
for (int i = 1; i <= 2 * n + 2; ++i) {
for (int j = 1; j <= 2 * n + 2; ++j) g[i][j] = {i, j, 0};
}
}
void add_edge(int u, int v, int w) {
if (u == v) return;
if (w > g[u][v].w) {
g[u][v] = {u, v, w};
g[v][u] = {v, u, w};
}
}
int e_delta(edge e) {
return lab[e.u] + lab[e.v] - g[e.u][e.v].w * 2;
}
void update_slack(int u, int x) {
if (!slack[x] || e_delta(g[u][x]) < e_delta(g[slack[x]][x])) slack[x] = u;
}
void set_slack(int x) {
slack[x] = 0;
for (int u = 1; u <= n; ++u) {
if (g[u][x].w && st[u] != x && S[st[u]] == 0) update_slack(u, x);
}
}
void q_push(int x) {
if (x <= n) q.push(x);
else {
for (int i = 0; i < flower_cnt[x]; ++i) q_push(flower[x][i]);
}
}
void set_st(int x, int b) {
st[x] = b;
if (x > n) {
for (int i = 0; i < flower_cnt[x]; ++i) set_st(flower[x][i], b);
}
}
void reverse_flower(int b, int l, int r) {
while (l < r) {
swap(flower[b][l], flower[b][r]);
++l, --r;
}
}
void rotate_flower(int b, int pr) {
int cnt = flower_cnt[b];
for (int i = 0; i < cnt; ++i) tmp[i] = flower[b][(i + pr) % cnt];
for (int i = 0; i < cnt; ++i) flower[b][i] = tmp[i];
}
int get_pr(int b, int xr) {
int pr = 0;
while (flower[b][pr] != xr) ++pr;
if (pr & 1) {
reverse_flower(b, 1, flower_cnt[b] - 1);
return flower_cnt[b] - pr;
}
return pr;
}
void set_match(int u, int v) {
match[u] = g[u][v].v;
if (u > n) {
edge e = g[u][v];
int xr = flower_from[u][e.u];
int pr = get_pr(u, xr);
for (int i = 0; i < pr; ++i) set_match(flower[u][i], flower[u][i ^ 1]);
set_match(xr, v);
rotate_flower(u, pr);
}
}
void augment(int u, int v) {
while (true) {
int xnv = st[match[u]];
set_match(u, v);
if (!xnv) return;
set_match(xnv, st[pa[xnv]]);
u = st[pa[xnv]], v = xnv;
}
}
int get_lca(int u, int v) {
static int tim = 0;
++tim;
while (u || v) {
if (u) {
if (vis[u] == tim) return u;
vis[u] = tim;
u = st[match[u]];
if (u) u = st[pa[u]];
}
swap(u, v);
}
return 0;
}
void add_blossom(int u, int lca, int v) {
int b = n + 1;
while (b <= nx && st[b]) ++b;
if (b > nx) ++nx;
lab[b] = 0, S[b] = 0, match[b] = match[lca];
flower_cnt[b] = 0;
flower[b][flower_cnt[b]++] = lca;
for (int x = u, y; x != lca; x = st[pa[y]]) {
flower[b][flower_cnt[b]++] = x;
y = st[match[x]];
flower[b][flower_cnt[b]++] = y;
q_push(y);
}
reverse_flower(b, 1, flower_cnt[b] - 1);
for (int x = v, y; x != lca; x = st[pa[y]]) {
flower[b][flower_cnt[b]++] = x;
y = st[match[x]];
flower[b][flower_cnt[b]++] = y;
q_push(y);
}
set_st(b, b);
for (int x = 1; x <= nx; ++x) {
g[b][x] = {b, x, 0};
g[x][b] = {x, b, 0};
}
for (int x = 1; x <= n; ++x) flower_from[b][x] = 0;
for (int i = 0; i < flower_cnt[b]; ++i) {
int xs = flower[b][i];
for (int x = 1; x <= nx; ++x) {
if (g[xs][x].w && (!g[b][x].w || e_delta(g[xs][x]) < e_delta(g[b][x]))) {
g[b][x] = g[xs][x];
g[x][b] = g[x][xs];
}
}
for (int x = 1; x <= n; ++x) {
if (flower_from[xs][x]) flower_from[b][x] = xs;
}
}
set_slack(b);
}
void expand_blossom(int b) {
for (int i = 0; i < flower_cnt[b]; ++i) set_st(flower[b][i], flower[b][i]);
int xr = flower_from[b][g[b][pa[b]].u];
int pr = get_pr(b, xr);
for (int i = 0; i < pr; i += 2) {
int xs = flower[b][i];
int xns = flower[b][i + 1];
pa[xs] = g[xns][xs].u;
S[xs] = 1, S[xns] = 0;
slack[xs] = 0;
set_slack(xns);
q_push(xns);
}
S[xr] = 1;
pa[xr] = pa[b];
for (int i = pr + 1; i < flower_cnt[b]; ++i) {
int xs = flower[b][i];
S[xs] = -1;
set_slack(xs);
}
st[b] = 0;
}
bool on_found_edge(edge e) {
int u = st[e.u], v = st[e.v];
if (S[v] == -1) {
pa[v] = e.u;
S[v] = 1;
int nu = st[match[v]];
slack[v] = slack[nu] = 0;
S[nu] = 0;
q_push(nu);
}
else if (S[v] == 0) {
int lca = get_lca(u, v);
if (!lca) {
augment(u, v);
augment(v, u);
return true;
}
else add_blossom(u, lca, v);
}
return false;
}
bool matching() {
for (int i = 1; i <= nx; ++i) S[i] = -1, slack[i] = 0;
while (!q.empty()) q.pop();
for (int x = 1; x <= nx; ++x) {
if (st[x] == x && !match[x]) {
pa[x] = 0;
S[x] = 0;
q_push(x);
}
}
if (q.empty()) return false;
while (true) {
while (!q.empty()) {
int u = q.front(); q.pop();
if (S[st[u]] == 1) continue;
for (int v = 1; v <= n; ++v) {
if (g[u][v].w && st[u] != st[v]) {
if (!e_delta(g[u][v])) {
if (on_found_edge(g[u][v])) return true;
}
else update_slack(u, st[v]);
}
}
}
int d = inf;
for (int u = 1; u <= n; ++u) {
if (S[st[u]] == 0) d = min(d, lab[u]);
}
for (int b = n + 1; b <= nx; ++b) {
if (st[b] == b && S[b] == 1) d = min(d, lab[b] / 2);
}
for (int x = 1; x <= nx; ++x) {
if (st[x] == x && slack[x]) {
if (S[x] == -1) d = min(d, e_delta(g[slack[x]][x]));
else if (S[x] == 0) d = min(d, e_delta(g[slack[x]][x]) / 2);
}
}
if (d == inf) return false;
for (int u = 1; u <= n; ++u) {
if (S[st[u]] == 0) {
if (lab[u] == d) return false;
lab[u] -= d;
}
else if (S[st[u]] == 1) lab[u] += d;
}
for (int b = n + 1; b <= nx; ++b) {
if (st[b] == b) {
if (S[b] == 0) lab[b] += d * 2;
else if (S[b] == 1) lab[b] -= d * 2;
}
}
while (!q.empty()) q.pop();
for (int x = 1; x <= nx; ++x) {
if (st[x] == x && slack[x] && st[slack[x]] != x && !e_delta(g[slack[x]][x])) {
if (on_found_edge(g[slack[x]][x])) return true;
}
}
for (int b = n + 1; b <= nx; ++b) {
if (st[b] == b && S[b] == 1 && !lab[b]) expand_blossom(b);
}
}
}
int solve() {
nx = n;
int cnt = 0, mx = 0;
for (int i = 0; i <= 2 * n + 2; ++i) {
lab[i] = match[i] = slack[i] = pa[i] = S[i] = vis[i] = 0;
st[i] = 0;
flower_cnt[i] = 0;
}
for (int i = 0; i <= n; ++i) st[i] = i;
for (int u = 1; u <= n; ++u) {
for (int v = 1; v <= n; ++v) {
flower_from[u][v] = (u == v ? u : 0);
mx = max(mx, g[u][v].w);
}
}
for (int u = 1; u <= n; ++u) lab[u] = mx;
while (matching()) ++cnt;
return cnt;
}
} blossom;
int new_node(int x, int &tot) {
ori[tot + 1] = x;
return ++tot;
}
void toggle_edge(int u, int v) {
if (u > v) swap(u, v);
sx[u][v] ^= 1;
}
void work() {
cin >> n >> m;
memset(idL, -1, sizeof(idL));
memset(idR, -1, sizeof(idR));
int tot = 0;
for (int i = 1; i <= n; ++i) {
if (i != n) idL[i] = new_node(i, tot);
}
for (int i = 1; i <= n; ++i) {
if (i != 1) idR[i] = new_node(i, tot);
}
blossom.init(tot);
for (int i = 1; i <= m; ++i) {
int u, v; cin >> u >> v;
if (idL[u] != -1 && idL[v] != -1) blossom.add_edge(idL[u], idL[v], big - 1);
if (idR[u] != -1 && idR[v] != -1) blossom.add_edge(idR[u], idR[v], big - 1);
}
init_cnt = 0;
for (int i = 2; i < n; ++i) {
blossom.add_edge(idL[i], idR[i], big);
init_u[++init_cnt] = idL[i], init_v[init_cnt] = idR[i];
}
int cnt = blossom.solve();
if (cnt != tot / 2) {
cout << -1 << '\n';
return;
}
for (int i = 1; i <= tot; ++i) {
adj[i].clear();
for (int j = 1; j <= tot; ++j) sx[i][j] = 0;
}
for (int i = 1; i <= tot; ++i) {
if (blossom.match[i] && i < blossom.match[i]) toggle_edge(i, blossom.match[i]);
}
for (int i = 1; i <= init_cnt; ++i) toggle_edge(init_u[i], init_v[i]);
for (int i = 1; i <= tot; ++i) {
for (int j = i + 1; j <= tot; ++j) {
if (sx[i][j]) {
adj[i].push_back(j);
adj[j].push_back(i);
}
}
}
int st = idL[1], ed = idR[n];
vector<int> aux, path;
int last = 0, cur = st;
while (true) {
aux.push_back(cur);
if (cur == ed) break;
int nxt = 0;
for (int v : adj[cur]) {
if (v != last) {
nxt = v;
break;
}
}
if (!nxt) {
cout << -1 << '\n';
return;
}
last = cur, cur = nxt;
if ((int)aux.size() > tot + 5) {
cout << -1 << '\n';
return;
}
}
path.push_back(1);
for (int i = 1; i < (int)aux.size(); ++i) {
int u = aux[i - 1], v = aux[i];
if (ori[u] != ori[v]) path.push_back(ori[v]);
}
if (path.back() != n || ((int)path.size() - 1) % 2) {
cout << -1 << '\n';
return;
}
cout << (int)path.size() - 1 << '\n';
for (int i = 0; i < (int)path.size(); ++i) {
if (i) cout << ' ';
cout << path[i];
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T--) work();
return 0;
}