0%

CF160D 题解

CF160D 题解

传送门:Edges in MST

思路

考虑 Kruskal 算法的过程,每次加入一个边权最小,且两个端点未被连通的边,加入 MST 中。

如果一个边,它在比它边权小的边完成了上述过程后,两个端点已经连通,那么就不会加入 MST 中,这样的边对应的答案是 none。

不好判断的地方在 any 和 at least one,即区分一个边是否能被替代。

一个边能被替代,则替代它的一定是和它边权相等的边,因为如果边权不等,那么最小生成树的边权和会发生变化,不符合最小。

现在,找到那些边权相等的边,把它们先都加入已经确定在最小生成树的边中。

现在,我们显然得到了一个新的图,而其中的边,其实必要的只有我们新加的边权相等的边,因为原来的边连接的点全部连通,组成了许多连通块,当然就可以缩成几个点。

假设我们已经缩点完毕,那么新加的边中,如果去掉一条边,整个图还是连通,而这个边在所有边加入之前,它的两个端点并未连通,就说明这个边处于一个环中,我们在环中不一定要选这个边让整个环连通,即它的答案是 at least one。至于那些去掉之后,整个图裂成两半的边,就是必需的,答案是 any。

这些必需的边,不就是割边吗,问题转化为求割边,可以用 Tarjan $O(n)$ 解决。

需要注意的是,我们使用并查集完成缩点,即一个连通块内的所有点都是并查集上祖先的点,每次完成加边后,由于整个图已经连通,要把这些边删掉,以保证时间复杂度。

这样一来,时间复杂度为 $O(n+n\log n) = O(n\log n)$。

总的来说,是一道不错的考察对 MST 的理解的题。

Code

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
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int n,m,head[N],tot,f[N],ans[N],dfn[N],low[N],cnt;
struct e{
int next,to,id;
} edge[N*2];
struct ed{
int x,y,w,id;
} ee[N];
bool cmp(ed x,ed y){
return x.w<y.w;
}
int get(int x){
if (x == f[x]) return x;
return f[x] = get(f[x]);
}
void add(int x,int y,int id){
edge[++tot].to = y;
edge[tot].next = head[x];
edge[tot].id = id;
head[x] = tot;
}
void dfs(int u,int fa){
int v;
dfn[u] = low[u] = ++cnt;
for (int i=head[u];i;i = edge[i].next){
v = edge[i].to;
if (!dfn[v]){
dfs(v,edge[i].id);
low[u] = min(low[u],low[v]);
if (dfn[u]<low[v]) ans[edge[i].id] = 1;
}
else if (edge[i].id!=fa) low[u] = min(low[u],dfn[v]);
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
int x,y,z;
for (int i=1;i<=m;i++){
cin>>x>>y>>z;
ee[i] = {x,y,z,i};
}
sort(ee+1,ee+1+m,cmp);
for (int i=1;i<=n;i++) f[i] = i;
for (int i=1,j;i<=m;i = j){
j = i+1;
while (ee[j].w == ee[j-1].w && j<=m) j++;
tot = cnt = 0;
for (int k=i;k<j;k++){
int x = get(ee[k].x),y = get(ee[k].y);
if (x == y){
ans[ee[k].id] = -1;
continue;
}
add(x,y,ee[k].id),add(y,x,ee[k].id);
}
for (int k=i;k<j;k++){
int x = get(ee[k].x),y = get(ee[k].y);
if (x == y) continue;
if (!dfn[x]) dfs(x,ee[k].id);
if (!dfn[y]) dfs(y,ee[k].id);
}
for (int k=i;k<j;k++){
int x = get(ee[k].x),y = get(ee[k].y);
if (x == y) continue;
f[x] = y,head[x] = head[y] = dfn[x] = dfn[y] = 0;
}
}
for (int i=1;i<=m;i++){
if (ans[i] == 1) cout<<"any"<<"\n";
else if (ans[i] == -1) cout<<"none"<<"\n";
else cout<<"at least one"<<"\n";
}
return 0;
}