题目传送门

思路

首先我们先找一个最大匹配,如果有点无法匹配那么答案显然是 $-1$。

接着我们统计最大匹配中黑边的出现次数,若为偶数,直接输出,否则考虑调整。

若本来的匹配是 $(1,5),(2,6),(3,4)$,现在我们要将匹配转化成 $(1,4),(2,5),(3,6)$,那么考虑按如下方式连边:

不难发现此时连成了一个环。

也就是说,如果我们按照“所有在最大匹配里的边左部点连到右部点,不在最大匹配里的边右部点连到左部点”的方式建出有向图,那么这张图上的环与调整方案一一对应。

同时,我们给每条边赋上颜色,边的颜色为这条边原先对应的那条无向边的颜色。

那么只要这张图存在一个奇环(出现了奇数次黑边的环),那么调整环上的匹配方案即可令答案合法。

暴力找环即可,时间复杂度 $\mathcal O(nm)$。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//A tree without skin will surely die.
//A man without face is invincible.
#include<bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i=j;i<=k;++i)
#define per(i,j,k) for(int i=j;i>=k;--i)
int const N=1e3+10;
int n,m,vis[N],dep[N],pre[N],matched[N],b[N][N],id[N][N];
vector<int>a[N];vector< pair<int,int> >c[N];
inline bool Hungary(int x,int co){
for (auto v:a[x]){
if (vis[v]==co) continue;
vis[v]=co;
if (!matched[v] || Hungary(matched[v],co)) return matched[v]=x,1;
}
return 0;
}
inline void dfs(int x){
vis[x]=1;
for (auto i:c[x]){
int v=i.first,w=i.second;
if (!vis[v]) dep[v]=dep[x]+w,pre[v]=x,dfs(v);
}
}
void solve(){
cin>>n>>m;
rep(i,1,2*n) a[i].clear(),matched[i]=vis[i]=0;
rep(i,1,2*n) rep(j,1,2*n) b[i][j]=-1;
rep(i,1,m){
int u,v,c;cin>>u>>v>>c;
a[u].push_back(v);
b[u][v]=b[v][u]=c;
id[u][v]=id[v][u]=i;
}
rep(i,1,n)
if (!Hungary(i,i)) return cout<<"-1\n",void();
int w=0;
rep(i,n+1,2*n) w+=b[i][matched[i]];
if (!(w&1)){
rep(i,n+1,2*n) cout<<id[i][matched[i]]<<' ';
cout<<'\n';
return;
}
rep(i,1,2*n) c[i].clear();
rep(i,n+1,n+n) c[matched[i]].push_back({i,b[i][matched[i]]});
rep(i,n+1,n+n) rep(j,1,n)
if (j!=matched[i] && b[i][j]!=-1) c[i].push_back({j,b[i][j]});
rep(i,1,n){
rep(j,1,n+n) vis[j]=dep[j]=pre[j]=0;
int tag=0;dfs(i);
rep(x,1,n+n)
for (auto s:c[x]){
int v=s.first,w=s.second;
if (v!=i) continue;
if (!vis[x]) continue;
if ((dep[x]-dep[v]+w)&1){tag=x;break;}
}
if (tag){
for (int nw=tag;nw!=i;nw=pre[nw]){
int k=pre[nw];
if (k>n) matched[k]=nw;
}
if (tag>n) matched[tag]=i;
rep(i,n+1,2*n) cout<<id[i][matched[i]]<<' ';
cout<<'\n';
return;
}
}
cout<<"-1\n";
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int t=1;
cin>>t;
while (t--) solve();
return 0;
}