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 107 108 109 110 111
| #include<vector> #include<algorithm> #include<cstdio> #include<iostream> #include<set> #include<cstring> #include<map> #include<cmath> #include<queue> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<int,pii> PII; const int maxn = 1e6+5;
int B[maxn]; int N,M; struct Edge { int from,to,val; bool operator<(const Edge& e)const { return val < e.val; } }; Edge E[maxn]; int Find(int n) { return B[n]==n?n:B[n]=Find(B[n]); }
void init() { for(int i=0;i<=N;i++) B[i] = i; } int vis[maxn]; int cnt = 0;
int MST() { sort(E,E+M); int ans = 0; for(int i=0;i<M;i++){ int t1 = Find(E[i].from); int t2 = Find(E[i].to); if(t1!=t2){ if(t1>t2)swap(t1,t2); B[t2] = t1; vis[cnt++] = i; ans += E[i].val; } if(cnt==N-1){ break; } } return ans; }
int SMT() { int res = 1<<30; for(int i=0;i<cnt;i++){ init(); int t = 0; int ans = 0; bool ok = 0; for(int j=0;j<M;j++){ if(j!=vis[i]){ int t1 = Find(E[j].from); int t2 = Find(E[j].to); if(t1!=t2){ t++; ans += E[j].val; if(t1>t2)swap(t1,t2); B[t2] = t1; } if(t==N-1){ ok = 1; break; } } } if(ok) res = min(res,ans); } if(res==1<<30)return -1; return res; }
int main(int argc, char const *argv[]) { int T = 0; cin >> T; while(T--){ memset(vis,0,sizeof(vis)); cnt = 0; cin >> N >> M; init(); for(int i=0;i<M;i++){ cin >> E[i].from >> E[i].to >> E[i].val; } int t1 = MST(); int t2 = SMT(); if(t1==t2){ cout << "Not Unique!" << endl; }else{ cout << t1 << endl; } } return 0; }
|