标签:des style blog http color os io strong
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 20679 | Accepted: 7255 |
Description
Input
Output
Sample Input
2 3 3 1 2 1 2 3 2 3 1 3 4 4 1 2 2 2 3 2 3 4 2 4 1 2
Sample Output
3 Not Unique!
Source
判断最小生成树是否唯一:
1、对图中每条边,扫描其它边,如果存在相同权值的边,则标记该边。
2、用kruskal或prim求出MST。
3、如果MST中无标记的边,则MST唯一;否则,在MST中依次去掉标记的边,再求MST,若求得MST权值和原来的MST 权值相同,则MST不唯一。
#include"stdio.h"
#include"string.h"
#include"iostream"
#include"algorithm"
using namespace std;
#define N 105
const int inf=0x7fffffff;
struct node
{
int u,v,w;
int eq,used,del;
}e[N*N];
int n,first,m;
int pre[N];
bool cmp(node a,node b)
{
return a.w<b.w;
}
int find(int x)
{
if(x!=pre[x])
pre[x]=find(pre[x]);
return pre[x];
}
int kruskal()
{
int i,f1,f2,ans,cnt;
ans=cnt=0;
for(i=1;i<=n;i++)
pre[i]=i;
for(i=0;i<m;i++)
{
if(e[i].del)
continue;
f1=find(e[i].u);
f2=find(e[i].v);
if(f1!=f2)
{
if(first)
e[i].used=1;
pre[f1]=f2;
ans+=e[i].w;
cnt++;
if(cnt>=n-1)
break;
}
}
return ans;
}
int main()
{
int i,j,T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
{
scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
e[i].del=e[i].eq=e[i].used=0;
}
sort(e,e+m,cmp);
for(i=0;i<m;i++)
{
for(j=i+1;j<m;j++)
{
if(e[i].w==e[j].w)
{
e[i].eq=e[j].eq=1;
}
else
break;
}
}
first=1;
int ans=kruskal();
first=0;
for(i=0;i<m;i++)
{
if(e[i].used&&e[i].eq)
{
e[i].del=1;
if(kruskal()==ans)
break;
e[i].del=0;
}
}
if(i<m)
printf("Not Unique!\n");
else
printf("%d\n",ans);
}
return 0;
}
poj 1679 The Unique MST (判断最小生成树是否唯一),布布扣,bubuko.com
poj 1679 The Unique MST (判断最小生成树是否唯一)
标签:des style blog http color os io strong
原文地址:http://blog.csdn.net/u011721440/article/details/38735547