//
// main.cpp
// Richard
//
// Created by 邵金杰 on 16/8/18.
// Copyright © 2016年 邵金杰. All rights reserved.
//
#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=100+5;
const int INF=100000000;
struct edge{
int u,v,w;
edge(int u,int v,int w): u(u),v(v),w(w) {}
bool operator < (const edge &e) const
{
return w>e.w;
}
};
int n,m;
vector<vector<edge> > G(maxn);
int vis[maxn],d[maxn][maxn],dist[maxn],map[maxn][maxn];
void Prim()
{
memset(vis,0,sizeof(vis));
memset(d,0,sizeof(d));
for(int i=1;i<=n;i++) dist[i]=INF;
priority_queue<edge> pq;
pq.push(edge(0,1,0));
edge nd(0,0,0);
int mst=0,cmst=INF;
while(!pq.empty())
{
do{
nd=pq.top();
pq.pop();
}while(vis[nd.v]&&!pq.empty());
if(vis[nd.v]==0)
{
map[nd.u][nd.v]=map[nd.v][nd.u]=0;
vis[nd.v]=1;
mst+=nd.w;
d[nd.u][nd.v]=nd.w;
for(int i=1;i<=n;i++)
{
if(vis[i])
{
d[i][nd.v]=max(d[i][nd.u],d[nd.u][nd.v]);
d[nd.v][i]=d[i][nd.v];
}
}
for(int i=0;i<G[nd.v].size();i++)
{
int e=G[nd.v][i].v;
if(!vis[e])
{
int w=G[nd.v][i].w;
if(dist[e]>w)
{
dist[e]=w;
pq.push(edge(nd.v,e,w));
}
}
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(map[i][j]) cmst=min(cmst,mst+map[i][j]-d[i][j]);
}
}
if(mst==cmst) printf("Not Unique!\n");
else printf("%d\n",mst);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(map,0,sizeof(map));
int a,b,c;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
G[i].clear();
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&a,&b,&c);
map[a][b]=map[b][a]=c;
G[a].push_back(edge(a,b,c));
G[b].push_back(edge(b,a,c));
}
Prim();
}
}
POJ 1679 The Unique MST(次小生成树)
最新推荐文章于 2019-05-04 17:33:50 发布
