跳到正文

题解

Codeforces Round 1112 editoral

_MCYYDS_约 99 分钟
原文
文章信息与版本

文章信息

发布
2026年7月27日
收录
2026年7月27日
更新
2026年11月9日
篇幅
约 99 分钟

版本

  1. v1当前

A Simple CF Round Editorial

A. Threshold Movement

Hints

** Hint 1 **

Can the element at position 11 move to the left?

** Hint 2 **

After the element at position 11 moves away, only the element at position 22 can fill position 11.

** Hint 3 **

Continuing to consider positions 2,3,…2,3,\ldots, the successful movement pattern is actually unique. Finally, we only need to determine whether there exists an integer threshold kk.

** Solution**

Let us consider what it means for each position to have exactly one element after the moves.

The element at position 11 cannot move left, only right, so we must have w1>kw_1>k. After it moves away, only the element at position 22 can fill position 11, so we must have w2<kw_2<k.

Thus positions 11 and 22 have been swapped. Continuing to look at the following elements, the only possible form is

1↔2,3↔4,5↔6,…1\leftrightarrow 2,\quad 3\leftrightarrow 4,\quad 5\leftrightarrow 6,\ldots

So nn must be even, with all odd positions moving right and all even positions moving left.

Let

L=max⁡i mod 2=0wi,R=min⁡i mod 2=1wiL=\max_{i\bmod 2=0}w_i,\qquad R=\min_{i\bmod 2=1}w_i

Then we only need there to exist an integer kk satisfying L<k<RL<k<R. Note that kk is an integer, so this is equivalent to L+2≤RL+2\le R.

That completes the solution. The time complexity per test case is O(n)O(n), and the extra space complexity is O(1)O(1).

Code

C++
#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 rr blocks total, then the number of adjacent equal pairs is n−rn-r.

** Hint 3 **

First set the length of all blocks to 11, then add the remaining 0\mathtt{0}‘s and 1\mathtt{1}‘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 rr blocks total, with lengths l1,l2,…,lrl_1,l_2,\ldots,l_r. A block of length lil_i contributes exactly li−1l_i-1 adjacent equal pairs, so the total is

∑i=1r(li−1)=n−r\sum_{i=1}^{r}(l_i-1)=n-r

So we need to construct exactly r=n−kr=n-k blocks.

Because k<nk<n, we have r≥1r\ge 1. Also, since n≥2n\ge 2, a string satisfying the count balance condition must contain both 0\mathtt{0} and 1\mathtt{1}, hence at least two blocks. Therefore when r=1r=1, i.e. k=n−1k=n-1, there is no solution.

Now consider r≥2r\ge 2. Let the block characters alternate starting with 0\mathtt{0}. Denote the number of 0\mathtt{0}-blocks and 1\mathtt{1}-blocks as

r0=⌈r2⌉,r1=⌊r2⌋r_0=\left\lceil\frac r2\right\rceil,\qquad r_1=\left\lfloor\frac r2\right\rfloor

We want the total counts of the two characters to be

c0=⌈n2⌉,c1=⌊n2⌋c_0=\left\lceil\frac n2\right\rceil,\qquad c_1=\left\lfloor\frac n2\right\rfloor

First assign one character to each block, which uses r0r_0 0\mathtt{0}‘s and r1r_1 1\mathtt{1}‘s. Since r≤nr\le n, we have r0≤c0r_0\le c_0 and r1≤c1r_1\le c_1.

Then add all remaining 0\mathtt{0}‘s to some 0\mathtt{0}-block and all remaining 1\mathtt{1}‘s to some 1\mathtt{1}-block, and finally concatenate all blocks in order. This way the difference in character counts is at most 11, the number of blocks is exactly rr, so the number of adjacent equal pairs is exactly n−r=kn-r=k.

The time complexity per test case is O(n)O(n), the total time complexity is O(∑n)O(\sum n), and the space complexity is O(n)O(n).

Code

C++
#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

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 mm. After fixing mm, 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 jj-th element of the retained subsequence, but also on the final length mm, because its right rank is m−j+1m-j+1.

So directly enumerate the final length mm.

After fixing mm, scan the original sequence from left to right, filling positions 1,2,…,m1,2,\ldots,m of the subsequence in order. When we are about to fill the jj-th position, element ii can be chosen if and only if

j∉[li,ri]j\notin[l_i,r_i]

and

m−j+1∉[ui,vi]m-j+1\notin[u_i,v_i]

Once the current element is available, choose it immediately.

Why is this greedy approach valid? Suppose some valid solution chooses element xx at position jj, while the greedy algorithm finds an earlier available element yy. Replacing xx with yy 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 mm from nn down to 11. The first feasible mm is the answer; if none is feasible, the answer is 00.

That completes the solution. The time complexity per test case is O(n2)O(n^2), and the space complexity is O(n)O(n).

Code

C++
#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

Hints

** Hint 1 **

The value nn 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 nn. 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 nn. This is because nn lies on only one side of the cut, and the maximum of the smaller interval is at most n−1n-1. So if there exists ai=na_i=n, the answer is 00.

Now consider the position of nn. For cut ii:

  • If nn is on the right, then aia_i equals the prefix maximum on the left;
  • If nn is on the left, then aia_i equals the suffix maximum on the right.

Therefore there must exist a dividing point cc such that a1,…,aca_1,\ldots,a_c is non-decreasing, while ac+1,…,an−1a_{c+1},\ldots,a_{n-1} is non-increasing. If both parts are non-empty, we must also have ac≠ac+1a_c\ne a_{c+1}, 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 cc 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 cc, merge

a1,a2,…,aca_1,a_2,\ldots,a_c

from the left and the reversed right side

an−1,an−2,…,ac+1a_{n-1},a_{n-2},\ldots,a_{c+1}

into a non-decreasing sequence. Process the ii-th value xx in order:

  • If xx appears for the first time, then in order for the maximum on this side to become xx for the first time, this position must be assigned xx, with no choice;
  • If xx has appeared before, then we only need to place some unused value less than xx here. Since i−1i-1 values have already been placed, the number of choices is x−i+1x-i+1.

Multiply the values x−i+1x-i+1 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 O(n)O(n). Since there are only a constant number of valid dividing points, the time complexity per test case is O(n)O(n), and the space complexity is O(n)O(n).

Code

C++
#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

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 xx, the change in the number of consecutive value blocks depends only on whether x−1x-1 and x+1x+1 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

qi=p((i−1) mod n)+1q_i=p_{((i-1)\bmod n)+1}

The prefix read starting from position ll becomes [l,l],[l,l+1],…,[l,l+n−1][l,l],[l,l+1],\ldots,[l,l+n-1].

Enumerate the right endpoint rr from left to right. When adding qrq_r, the range of starting positions whose current prefix ends exactly at rr is

L=max⁡(1,r−n+1),R=min⁡(r,n)L=\max(1,r-n+1),\qquad R=\min(r,n)

Let the newly added value be xx. Since the current prefix length does not exceed nn, the same permutation value does not appear twice. After adding xx, the change in the number of consecutive value blocks depends only on whether neighboring values have already appeared:

Δ=1−[x−1 already appeared]−[x+1 already appeared]\Delta=1-[x-1\text{ already appeared}]-[x+1\text{ already appeared}]

That is, first treat xx 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 last⁡v\operatorname{last}_v be the last position where value vv appeared before position rr. For starting position ll, value vv has appeared in [l,r−1][l,r-1] if and only if last⁡v≥l\operatorname{last}_v\ge l.

So adding xx only requires three range additions:

  1. Add 11 to [L,R][L,R];
  2. If x−1x-1 exists, subtract 11 from [L,min⁡(R,last⁡x−1)][L,\min(R,\operatorname{last}_{x-1})];
  3. If x+1x+1 exists, subtract 11 from [L,min⁡(R,last⁡x+1)][L,\min(R,\operatorname{last}_{x+1})].

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 2n−12n-1 right endpoints in total, with only a constant number of range operations each time, so the time complexity is O(nlog⁡n)O(n\log n), and the space complexity is O(n)O(n).

Code

C++
#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

Hints

** Hint 1 **

Compare adjacent rows. After fixing a pair of adjacent rows, the 2×22\times2 condition forces the XOR difference between corresponding positions in the two rows to alternate according to parity.

** Hint 2 **

We need many hh satisfying

{0,1,…,n−1}xor⁡h={0,1,…,n−1}\{0,1,\ldots,n-1\}\mathbin{\operatorname{xor}}h=\{0,1,\ldots,n-1\}

What is the size of the XOR stabilizer of this set?

** Hint 3 **

When nn is a power of two, pair elements as y↔y⊕xy\leftrightarrow y\oplus x, then place several whole pairs in odd positions.

** Solution**

First consider when a solution exists. Let S={0,1,…,n−1}S=\{0,1,\ldots,n-1\}, and define the difference between adjacent rows in column jj as

di(j)=Ai,j⊕Ai+1,jd_i(j)=A_{i,j}\oplus A_{i+1,j}

The adjacent 2×22\times2 submatrix condition gives

di(j+1)=di(j)⊕xd_i(j+1)=d_i(j)\oplus x

So after fixing the parity of the column, the XOR difference between the two rows is a fixed value. At least ⌈n/2⌉\lceil n/2\rceil rows have the same parity, and each column must be a permutation, so we need at least ⌈n/2⌉\lceil n/2\rceil distinct hh such that S⊕h=SS\oplus h=S.

Let L=lowbit⁡(n)L=\operatorname{lowbit}(n). The XOR stabilizer of the interval SS is exactly

{0,1,…,L−1}\{0,1,\ldots,L-1\}

On one hand, any value less than LL only permutes positions within blocks of length LL. On the other hand, if we write h=gL+rh=gL+r with 0≤r<L0\le r<L, then a nonzero gg would pair up block indices; but the number of blocks n/Ln/L is odd, so the entire set of block indices cannot remain invariant. Therefore we must have g=0g=0.

Thus the necessary condition is

lowbit⁡(n)≥⌈n2⌉\operatorname{lowbit}(n)\ge\left\lceil\frac n2\right\rceil

This only holds when nn is a power of two. Additionally, when n=2n=2, each value appears twice in any 2×22\times2 Latin square, so the XOR of all four numbers is necessarily 00; hence for x>0x>0 there is still no solution.

Now consider the construction.

If x=0x=0, directly set

Ai,j=i⊕jA_{i,j}=i\oplus j

Since nn is a power of two, XORing with a fixed value permutes SS, so each row and each column is a permutation; in each adjacent 2×22\times2, the indices all appear twice, so the XOR is 00.

Now suppose x>0x>0, nn is a power of two, and n≥4n\ge4. The map y↦y⊕xy\mapsto y\oplus x partitions SS into n/2n/2 pairs. Choose n/4n/4 of these pairs to form the set OO, and let the remaining values form the set EE, so that

∣E∣=∣O∣=n2,E⊕x=E,O⊕x=O|E|=|O|=\frac n2,\qquad E\oplus x=E,\qquad O\oplus x=O

Construct a permutation pp that places EE in even positions and OO in odd positions, then output

Ai,j=pi⊕pj⊕((i mod 2)(j mod 2)x)A_{i,j}=p_i\oplus p_j\oplus\bigl((i\bmod2)(j\bmod2)x\bigr)

Even rows are just fixed XOR translations of pp. In odd rows, even columns come from pi⊕Ep_i\oplus E, and odd columns come from pi⊕(O⊕x)=pi⊕Op_i\oplus(O\oplus x)=p_i\oplus O, together still forming SS. The formula is symmetric in ii and jj, so the columns also satisfy the condition.

Finally, look at any adjacent 2×22\times2. The four pp terms cancel out in pairs, and among the four parity combinations exactly one is (1,1)(1,1), so the extra XOR is exactly xx.

The output itself has n2n^2 numbers, so the time complexity is O(n2)O(n^2), and the extra space complexity is O(n)O(n).

Code

C++
#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 kik^i as a block. What smaller blocks is it composed of?

** Hint 2 **

If we add the same value to every character and take modulo kk, 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 n−1n-1. 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 Bi,jB_{i,j} be the standard block of length kik^i with an overall character shift of jj. Then

Bi,j=Bi−1,jBi−1,j+1⋯Bi−1,j+k−1B_{i,j}=B_{i-1,j}B_{i-1,j+1}\cdots B_{i-1,j+k-1}

where all shifts are taken modulo kk. This is exactly how the digit sum changes when the highest digit increases.

For the current pattern string tt, we maintain three pieces of information for each block:

  • The number of occurrences of tt inside the block;
  • The first n−1n-1 characters of the block;
  • The last n−1n-1 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 n−1n-1 characters.

Keeping the entire string directly would still be too slow. Let xx be the smallest integer satisfying n≤kxn\le k^x. 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 k2k^2 possibilities total, which can be precomputed at once.

For a query interval [l,r][l,r], recursively split it in base kk into O(klog⁡kV)O(k\log_k V) 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 nn, 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

O(∑n⋅k2+qlog⁡kV⋅k2)O\left(\sum n\cdot k^2+q\log_k V\cdot k^2\right)

where V=1017V=10^{17}. The space complexity is O(n+k2log⁡kV)O(n+k^2\log_k V).

Code

C++
#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 kk. Each block is a cyclic shift of 012…(k−1)\mathtt{012\ldots(k-1)}, and after compressing each block to its shift value, we obtain the same infinite string again.

** Hint 2 **

Let

di=(ti−ti−1+k) mod kd_i=(t_i-t_{i-1}+k)\bmod k

Within a complete block we always have di=1d_i=1. All positions where di≠1d_i\ne1 must have the same residue modulo kk.

** Hint 3 **

If the positions not equal to 11 determine the block boundaries, compress both the pattern string and the query interval by a factor of about kk and recurse; if there are no such positions, the valid pattern length cannot exceed 2k2k.

** Solution**

First look at the block structure of the infinite string ss. Each block of length kk is a cyclic shift of

012…(k−1)\mathtt{012\ldots(k-1)}

If we replace each entire block by its shift value, the resulting string is still the original ss. So as long as we can align the pattern string tt with these blocks, we can reduce both the pattern length and the query interval by a factor of about kk.

How do we find the alignment? Take the modulo-kk difference of tt:

di=(ti−ti−1+k) mod kd_i=(t_i-t_{i-1}+k)\bmod k

Inside a complete cyclic block, adjacent differences are always 11. Therefore all positions where di≠1d_i\ne1 must fall on the same type of block boundary, meaning their residues modulo kk 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 tt according to this boundary, compress each complete block into one shift value, and map the interval [l,r][l,r] to a compressed interval based on the lengths of the left and right partial blocks, then recurse.

The remaining case is when all di=1d_i=1, so the boundaries are not determined. Note that ss cannot contain a substring longer than 2k2k with all adjacent differences equal to 11. Such a substring would give three consecutive terms si=si+k=si+2ks_i=s_{i+k}=s_{i+2k}. But si=si+ks_i=s_{i+k} requires that the corresponding higher digit of ii changes by 11 with a carry; the same condition cannot hold for both ii and i+ki+k consecutively.

So if the pattern can occur, we must have n≤2kn\le2k. We can enumerate the block boundaries, reducing the compressed pattern to a string of length at most 22; when n≤kn\le k, 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 11 or 22.

For length 11, every complete block of length kk contains each character exactly once, and only the partial block at the end needs to be computed directly.

For length 22, precompute

fp,q,x,yf_{p,q,x,y}

as the number of occurrences of the pair xyxy in the first qkpqk^p characters. The next level is formed by kk 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 kk and subtract to obtain the interval answer.

The total time complexity is

O(qklog⁡kV+∑n+k3log⁡kV+klog⁡k2V)O\left(qk\log_k V+\sum n+k^3\log_k V+k\log_k^2V\right)

where V=1017V=10^{17}.

Code

C++
#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

Hints

** Hint 1 **

In a simple path, the two endpoints have degree 11, all other used vertices have degree 22, and unused vertices have degree 00. Can we encode this degree condition using matching?

** Hint 2 **

Split each vertex into left and right copies, but delete R(1)R(1) and L(n)L(n). Original edges connect copies on the same layer; unused internal vertices use cross-layer edges to match their two copies.

** Hint 3 **

Assign weight MM to cross-layer edges and weight M−1M-1 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 11 to vertex nn satisfies:

  • Vertices 11 and nn have degree 11 in the path;
  • All other used vertices have degree 22;
  • Unused vertices have degree 00.

For each vertex vv of the original graph G=(V,E)G=(V,E), create two copies L(v)L(v) and R(v)R(v), then delete R(1)R(1) and L(n)L(n). The vertex set of the auxiliary graph G′=(V′,E′)G'=(V',E') is

V′={L(v)∣v≠n}∪{R(v)∣v≠1}V'=\{L(v)\mid v\ne n\}\cup\{R(v)\mid v\ne1\}

Deleting these two copies ensures that vertices 11 and nn 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 (u,v)∈E(u,v)\in E, as long as both endpoint copies exist, add same-layer edges (L(u),L(v))(L(u),L(v)) and (R(u),R(v))(R(u),R(v)), each with weight M−1M-1.

For each internal vertex v∉{1,n}v\notin\{1,n\}, add a cross-layer edge (L(v),R(v))(L(v),R(v)) with weight MM. Here we take any constant M>∣V′∣M>|V'|.

Compute a maximum weight matching in the general graph G′G'. If it is not a perfect matching, then no valid path exists; otherwise we can recover the answer from it. Because M>∣V′∣M>|V'|, 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 SS.

For an internal vertex vv, if SS chooses the cross-layer edge (L(v),R(v))(L(v),R(v)), then vv is considered unused, corresponding to degree 00 in the original graph.

Otherwise, L(v)L(v) and R(v)R(v) are each matched via two same-layer edges to other copies, which corresponds to vv having degree 22 in the original graph.

Vertices 11 and nn each have only one copy and no cross-layer edge, so their degrees are naturally 11.

Therefore, mapping all chosen same-layer edges back to the original graph gives a path from 11 to nn plus some cycles.

Why the Path Length is Even

Suppose there exists an even-length simple path

p0=1,p1,p2,…,pL=np_0=1,p_1,p_2,\ldots,p_L=n

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 LL is even, the last edge falls on the right layer and connects to the existing R(n)R(n). All internal vertices not on the path choose their own cross-layer edges, yielding a perfect matching.

Conversely, from any perfect matching, the 11-to-nn component starts at L(1)L(1), alternates between the left and right layers using same-layer edges, and eventually reaches R(n)R(n), so the number of original edges in it must be even. This component has only two vertices of degree 11, and all other vertices have degree 22, so it corresponds to an even-length simple path.

Why Maximum Weight Eliminates Cycles

Suppose the recovered result also contains a cycle with cc vertices. This cycle uses cc same-layer matching edges of weight M−1M-1, with total weight c(M−1)c(M-1).

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 cMcM, 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 MM, and same-layer edges have weight M−1M-1, 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 2n−22n-2 vertices and at most 2m+n−22m+n-2 edges, requiring a general graph maximum weight matching algorithm, such as the weighted blossom algorithm, with complexity O(∣V′∣3)O(|V'|^3).

After obtaining the matching:

  1. If the matching size is not ∣V′∣/2|V'|/2, output −1-1;
  2. Take the symmetric difference of the matching edge set and the set of cross-layer edges for all internal vertices;
  3. The cross-layer edges of unused vertices cancel out, and the remaining auxiliary graph is exactly a path from L(1)L(1) to R(n)R(n);
  4. 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

C++
#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;
}
原文