题目链接:
POJ 1258 Agri-Net
题意:
有n个点,并给出任意两点间的距离。求最小生成树路径和。
分析:
Prim Algorithm
//740K 16MS
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;const int maxn=110;
const int INF=0x3f3f3f3f;int n,ans;
int vis[maxn],dis[maxn],map[maxn][maxn];int main()
{
#ifdef LOCALfreopen("in.txt","r",stdin);//freopen("out.txt","w",stdout);
#endifwhile(~scanf("%d",&n)){for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)scanf("%d",&map[i][j]);//Prim Algorithmmemset(vis,0,sizeof(vis));vis[1]=1;ans=0;for(int i=1;i<=n;i++)dis[i]=map[1][i];for(int i=1;i<n;i++){int k=-1;int tmp=INF;for(int j=1;j<=n;j++){if(!vis[j]&&dis[j]<tmp){tmp=dis[j];k=j;}}vis[k]=1;ans+=tmp;//printf("%d\n",tmp);for(int j=1;j<=n;j++){if(!vis[j]&&dis[j]>map[k][j]) dis[j]=map[j][k];}}printf("%d\n",ans);}return 0;
}