Codeforces Round 1112 editoral
A Simple CF Round Editorial
A. Threshold Movement
-
Idea:aaa_Pigeon2
-
Solution:aaa_Pigeon2
Hints
Hint 1
Can the element at position
Hint 2
After the element at position
Hint 3
Continuing to consider positions
Solution
Let us consider what it means for each position to have exactly one element after the moves.
The element at position
Thus positions
So
Let
Then we only need there to exist an integer
That completes the solution. The time complexity per test case 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
-
Idea:_MCYYDS_
-
Solution:_MCYYDS_
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
Hint 3
First set the length of all blocks to
Solution
Define a block as a maximal consecutive segment of identical characters in the string. Suppose the string has
So we need to construct exactly
Because
Now consider
We want the total counts of the two characters to be
First assign one character to each block, which uses
Then add all remaining
The time complexity per test case 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
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
So directly enumerate the final length
After fixing
and
Once the current element is available, choose it immediately.
Why is this greedy approach valid? Suppose some valid solution chooses element
Enumerate
That completes the solution. The time complexity per test case 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
Hint 2
Enumerate the dividing point corresponding to the position of
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
Now consider the position of
- If
n is on the right, thena_i equals the prefix maximum on the left; - If
n is on the left, thena_i equals the suffix maximum on the right.
Therefore there must exist a dividing point
We enumerate all
After fixing
from the left and the reversed right side
into a non-decreasing sequence. Process the
- If
x appears for the first time, then in order for the maximum on this side to becomex for the first time, this position must be assignedx , with no choice; - If
x has appeared before, then we only need to place some unused value less thanx here. Sincei-1 values have already been placed, the number of choices isx-i+1 .
Multiply the values
The entire merging process 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
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
Enumerate the right endpoint
Let the newly added value be
That is, first treat
How do we determine this for all starting positions simultaneously? Let
So adding
- Add
1 to[L,R] ; - If
x-1 exists, subtract1 from[L,\min(R,\operatorname{last}_{x-1})] ; - If
x+1 exists, subtract1 from[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
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
Hint 2
We need many
What is the size of the XOR stabilizer of this set?
Hint 3
When
Solution
First consider when a solution exists. Let
The adjacent
So after fixing the parity of the column, the XOR difference between the two rows is a fixed value. At least
Let
On one hand, any value less than
Thus the necessary condition is
This only holds when
Now consider the construction.
If
Since
Now suppose
Construct a permutation
Even rows are just fixed XOR translations of
Finally, look at any adjacent
The output itself has
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)
-
Idea:131241
-
Solution:131241
Hints
Hint 1
View a prefix of length
Hint 2
If we add the same value to every character and take modulo
Hint 3
For each block, store the internal occurrence count, as well as the prefix and suffix of length at most
Solution
Consider the self-similar structure of the infinite string. Let
where all shifts are taken modulo
For the current pattern string
- The number of occurrences of
t inside the block; - The first
n-1 characters of the block; - The last
n-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
Keeping the entire string directly would still be too slow. Let
For a query interval
In the stages where the block length is less than
where
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)
-
Idea:131241
-
Solution:131241
Hints
Hint 1
Partition the infinite string into blocks of length
Hint 2
Let
Within a complete block we always have
Hint 3
If the positions not equal to
Solution
First look at the block structure of the infinite string
If we replace each entire block by its shift value, the resulting string is still the original
How do we find the alignment? Take the modulo-
Inside a complete cyclic block, adjacent differences are always
If exactly one residue appears, the block boundaries are uniquely determined. Cut
The remaining case is when all
So if the pattern can occur, we must have
Finally we only need to answer the occurrence count of a pattern of length
For length
For length
as the number of occurrences of the pair
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
Hint 2
Split each vertex into left and right copies, but delete
Hint 3
Assign weight
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
- Vertices
1 andn have degree1 in the path; - All other used vertices have degree
2 ; - Unused vertices have degree
0 .
For each vertex
Deleting these two copies ensures that vertices
For each original edge
For each internal vertex
Compute a maximum weight matching in the general graph
Meaning of a Perfect Matching
Consider a perfect matching
For an internal vertex
Otherwise,
Vertices
Therefore, mapping all chosen same-layer edges back to the original graph gives a path from
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
Conversely, from any perfect matching, the
Why Maximum Weight Eliminates Cycles
Suppose the recovered result also contains a cycle with
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
Why We Obtain the Shortest Path
Any perfect matching has the same number of edges. Cross-layer edges have weight
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
After obtaining the matching:
- If the matching size is not
|V'|/2 , output-1 ; - 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
L(1) toR(n) ; - 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;
}