题目:
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 0
3 5 <div style='font-family:Times New Roman;font-size:14px;background-color:F4FBFF;border:#B7CBFF 1px dashed;padding:6px'><div style='font-family:Arial;font-weight:bold;color:#7CA9ED;border-bottom:#B7CBFF 1px dashed'><i>Hint</i></div>Hint</div> Huge input, scanf is recommended.
想法:直接用prim算法。。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define inf 0x3f3f3f3;
int mat[11000][11000],dis[11000],mark[11000];
int prim(int n,int sta)
{
int i,j,flag,sum = 0;
for (i = 1;i<=n;i ++)
{
dis[i] = mat[sta][i];
mark[i] = 0;
}
mark[sta] = 1;
for (i = 2;i<=n;i ++)
{
int min = inf;
for (j = 1;j <=n;j ++)
if (!mark[j] && dis[j] < min)
min = dis[j],flag = j;
mark[flag] = 1;
sum += dis[flag];
for (j = 1;j <=n;j ++)
if (dis[j] > mat[flag][j])
dis[j] = mat[flag][j];
}
return sum;
}
int main()
{
int m,n,i,a,b,t;
while(cin>>n&&n!=0)
{
for(i=1;i<=n*(n-1)/2;i++)
{
cin>>a>>b>>t;
mat[a][b]=mat[b][a]=t;
}
m=prim(n,1);
cout<<m<<endl;
}
return 0;
}