标签:ring poj1679 c++ int algo res mat 相同 turn
n个点m条边,判断最小生成树是否唯一
求出次小生成树和最小生成树大小是否相同即可
#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;
}
标签:ring poj1679 c++ int algo res mat 相同 turn
原文地址:https://www.cnblogs.com/django-lf/p/9735320.html