最小生成树问题 | ||||||
| ||||||
Description | ||||||
一个有 n 个结点的无向连通图的生成树是原图的极小连通子图,且包含原图中的所有 n 个结点, 并且有保持图联通的最少的边。求解最小生成树的一个算法是Kruskal提出的kruskal算法,该算 法每次找到所有边中权值最小的一条,并判断该边的加入是否会让最小生成树出现环,如果不会则将 其作为最小生成树的一条边。 现在给出一个图的节点数N和边数M以及每条边的权值,求出该图的最小生成树的所有边权值总和。 | ||||||
Input | ||||||
每组输入第一行为N和M,N<=10000,M<=50000,然后为M行,每行三个整数a,b,w,表示a,b之间有 一条权值为w的边。 | ||||||
Output | ||||||
如果该图无法生成最小生成树,即原图不连通,则输出-1,否则输出最小生成树的长度。 | ||||||
Sample Input | ||||||
3 3 1 2 1 1 3 2 2 3 4 | ||||||
Sample Output | ||||||
3 |
不想说啥。。看代码吧/。//
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
struct coor
{
int x,y,d;
friend bool operator <(coor a,coor b)
{
return a.d>b.d;
}
};
int pre[10003];
priority_queue<coor>q;
int find(int x)
{
if(x!=pre[x])
return pre[x]=find(pre[x]);
else return x;
}
int ans=0;
void coin(coor x)
{
int a=find(x.x);
int b=find(x.y);
if(a!=b)
{
pre[a]=b;
// printf(" ans:%d %d\n",a,b);
ans+=x.d;
}
}
void init(int n)
{
for(int i=1; i<=n; i++)
{
pre[i]=i;
}
}
int judge(int n)
{
int num=find(1);
for(int i=2;i<=n;i++)
{
if(find(i)!=num)
return 0;
}
return 1;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)==2)
{
init(n);
ans=0;
while(!q.empty())
q.pop();
coor a,b;
for(int i=1; i<=m; i++)
{
scanf("%d%d%d",&a.x,&a.y,&a.d);
q.push(a);
}
while(!q.empty())
{
b=q.top();
coin(b);
q.pop();
}
if(judge(n))
printf("%d\n",ans);
else printf("-1\n");
}
}