當N爲0時,輸入結束,該用例不被處理。
Output對每個測試用例,在1行裏輸出最小的公路總長度。
Sample Input
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0Sample Output
3 5
這題是kruskal算法,模板題吧 ,可以用快排 也能用sort。
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
struct edge
{
int u,v,w;
}map[10000];
int father[10000]= {0},sum=0,ans=0;
void quicksort(int left,int right)
{
int i,j;
struct edge t;
if(left>right)
return;
i=left;
j=right;
while(i!=j)
{
while(map[j].w>=map[left].w&&i<j)
j--;
while(map[i].w<=map[left].w&&i<j)
i++;
if(i<j)
{
t=map[i];
map[i]=map[j];
map[j]=t;
}
}
t=map[left];
map[left]=map[i];
map[i]=t;
quicksort(left,i-1);
quicksort(i+1,right);
return ;
}
int cmp(edge a,edge b)
{
return a.w<b.w;
}
int find_father(int x)
{
if(x==father[x]) return x;
else
{
father[x]=find_father(father[x]);
return father[x];
}
}
int merge(int u,int v)
{
int x=find_father(u);
int y=find_father(v);
if(x!=y)
{
father[y]=x;
return 1;
}
return 0;
}
int main()
{
int n,m;
while(~scanf("%d",&n))//頂點
{
if(n==0) break;
sum=0;
m=n*(n-1)/2;//邊
for(int i=1; i<=m; i++)
{
scanf("%d%d%d",&map[i].u,&map[i].v,&map[i].w);
}
quicksort(1,m);
//sort(map+1,map+m+1,cmp);
for(int i=1; i<=n; i++)
{
father[i]=i;
}
for(int i=1; i<=m; i++)
{
if(merge(map[i].u,map[i].v))
{
ans++;
sum+=map[i].w;
}
}
printf("%d\n",sum);
}
return 0;
}