forked from marioyc/Online-Judge-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1679 - The Unique MST.cpp
executable file
·106 lines (76 loc) · 1.54 KB
/
1679 - The Unique MST.cpp
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <cstdio>
#include <algorithm>
using namespace std;
#define MAX_V 100
struct edge{
int u,v,w;
edge(){}
edge(int u, int v, int w) : u(u), v(v), w(w){}
bool operator < (edge X)const{
return w<X.w;
}
bool operator != (edge X)const{
return (u!=X.u || v!=X.v);
}
}L[MAX_V*MAX_V],MST[MAX_V];
int parent[MAX_V],rank[MAX_V];
void Make_Set(int x){
parent[x] = x; rank[x] = 0;
}
int Find(int x){
if(parent[x]!=x) parent[x] = Find(parent[x]);
return parent[x];
}
void Union(int x, int y){
int PX = Find(x), PY = Find(y);
if(rank[PX]>rank[PY]) parent[PY] = PX;
else{
parent[PX] = PY;
if(rank[PX]==rank[PY]) ++rank[PY];
}
}
int V,E;
int erase(edge &e){
int ret = 0, cont = V;
for(int i = 0;i<V;++i) Make_Set(i);
for(int i = 0,j = 0;i<E;++i){
if(e!=L[i] && Find(L[i].u)!=Find(L[i].v)){
Union(L[i].u,L[i].v);
ret += L[i].w;
--cont;
}
}
if(cont!=1) return -1;
return ret;
}
int main(){
int T,u,v,w;
scanf("%d",&T);
while(T--){
scanf("%d %d",&V,&E);
for(int i = 0;i<E;++i){
scanf("%d %d %d",&u,&v,&w);
--u; --v;
L[i] = edge(u,v,w);
}
sort(L,L+E);
int MST_W = 0;
for(int i = 0;i<V;++i) Make_Set(i);
for(int i = 0,j = 0;i<E;++i){
if(Find(L[i].u)!=Find(L[i].v)){
Union(L[i].u,L[i].v);
MST_W += L[i].w;
MST[j++] = L[i];
}
}
bool unique = true;
for(int i = 0;i+1<V;++i){
int aux = erase(MST[i]);
if(aux!=-1 && aux==MST_W)
unique = false;
}
if(unique) printf("%d\n",MST_W);
else printf("Not Unique!\n");
}
return 0;
}