首页 > 代码库 > zoj 1372
zoj 1372
#include<iostream>
#include<cstdio>
using namespace std;
#define N 1005
int a[N][N],low[N],n,ans;
int b[N];
int min(int x,int y)
{ return x<y?x:y; }
void prim(int u0)
{
int i,j,m,k;
ans=0;
for (i=1;i<n;i++) low[i]=a[u0][i];
low[u0]=-1;
for (i=1;i<n;i++)
{
m=1<<20;
for (j=0;j<n;j++)
if (low[j]!=-1&&low[j]<m)
{ m=low[j]; k=j; }
ans+=m;
low[k]=-1;
for (j=0;j<n;j++)
if (low[j]!=-1)low[j]=min(low[j],a[k][j]);
}
}
int main()
{
int i,j,t;
while(scanf("%d",&n)&&n)
{
scanf("%d",&t);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=1<<20;
for(i=0;i<t;i++)
{
int ai,bi,ci;
scanf("%d%d%d",&ai,&bi,&ci);
if(a[ai-1][bi-1]>ci)
{
a[ai-1][bi-1]=ci;
a[bi-1][ai-1]=ci;
}
}
ans=0;
if(n!=1)
prim(0);
cout<<ans<<endl;
}
return 0;
}