这道题是我们jn市组织的集训讲解的,写篇题解
讲解师讲的比较抽象,比较神秘
对于随意交换,不限次数,我们考虑这道题怎么做
其实就是树的最大匹配数量
考虑贪心,从叶子节点找,写个拓扑
如图就是最大匹配,可以证明不存在更优解
—————————————分割线————————————
我们大胆猜测,这个题的最优也是最大匹配
考虑到只能有一次,我们可以将所有最大匹配链接,将相同颜色的链接,就类似于下图
由于每个相同的连一块,匹配连一块,实际要么十条链,要么是条环。
我们直接假设所以都匹配上,先从任意位置当环跳,进行匹配,在跑剩余点
因为如图是一个类似线性数组的东西,考虑类似冒泡排序,交换相同,那么一定会换出我们上述最大匹配
这个题的最优也是最大匹配
考虑做法,将所述拼接 考虑贪心,从叶子节点找,写个拓扑
直接暴力跳环,跳两次即可
代码如下
#include<bits/stdc++.h>
#define int long long
using namespace std;
int t, n, w[201000], head[201000], tot, ru[201000], vis[201000], pos[101000], match1[201000], match[201000], vis2[201000];
vector<pair<int, int> > kuai;
struct node{
int v, nxt;
}a[401000];
void add(int u, int v){
a[++tot].v = v;
a[tot].nxt = head[u];
head[u] = tot;
}
queue<int> q;
void work(){
while(!q.empty()) q.pop();
kuai.clear();
cin >> n;
tot = 0;
for(int i = 1;i <= 2 * n;i++) head[i] = ru[i] = vis[i] = match1[i] = match[i] = vis2[i] = 0;
for(int i = 1;i <= n;i++) pos[i] = 0;
for(int i = 1;i <= 2 * n;i++){
cin >> w[i];
if(!pos[w[i]]) pos[w[i]] = i;
else{
match1[i] = pos[w[i]];
match1[pos[w[i]]] = i;
}
}
for(int i = 1;i < 2 * n;i++){
int u, v;
cin >> u >> v;
add(u, v);
add(v, u);
ru[u]++, ru[v]++;
}
for(int i = 1;i <= 2 * n;i++){
if(ru[i] == 1){
q.push(i);
}
}
while(!q.empty()){
int x = q.front();
q.pop();
if(ru[x] != 1) continue;
int y = 0;
for(int i = head[x];i;i = a[i].nxt){
if(ru[a[i].v] > 0){
y = a[i].v;
break;
}
}
if(y == 0){
ru[x] = 0;
continue;
}
vis[x] = vis[y] = 1;
kuai.push_back(make_pair(x, y));
ru[x] = 0;
ru[y] = 0;
for(int i = head[y];i;i = a[i].nxt){
int v = a[i].v;
if(ru[v] > 0){
ru[v]--;
if(ru[v] == 1) q.push(v);
}
}
}
for(auto x : kuai){
match[x.first] = x.second;
match[x.second] = x.first;
}
vector<pair<int, int> > ans;
for(int _ = 1;_ <= 2;_++){
for(int st = 1;st <= 2 * n;st++){
if(vis2[st]) continue;
if(_ == 1 && match[st] != 0) continue;
if(_ == 2 && match[st] == 0) continue;
vector<int> cyc;
int now = st;
while(true){
vis2[now] = 1;
cyc.push_back(now);
int p = match1[now];
if(vis2[p]) break;
vis2[p] = 1;
cyc.push_back(p);
if(match[p] == 0) break;
int s = match[p];
if(vis2[s]) break;
now = s;
}
for(int i = 0;i < cyc.size() / 2;i++){
int j = cyc.size() / 2 - 1 - i;
if(i < j){
int u = cyc[2 * i], v = cyc[2 * j];
if(u > v) swap(u, v);
ans.push_back(make_pair(u, v));
}
int temp = cyc.size() / 2;
int h = (((temp) - 2 - i) % (temp) + (temp)) % (temp);
if(i < h){
int u = cyc[2 * i + 1], v = cyc[2 * h + 1];
if(u > v) swap(u, v);
ans.push_back(make_pair(u, v));
}
}
}
}
cout << ans.size() << "\n";
for(auto x : ans){
cout << x.first << " " << x.second << "\n";
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> t;
while(t--) work();
return 0;
}