prime算法的模板题
给你村庄的距离矩阵,输出最小生成树的长
prime模板:
> int prim(int cost[][maxn],int n) {
> int ans=0;
> mem(vis);
> vis[0]=true;
> for(int i=1;i<n;i++)
> {
> low[i]=cost[0][i];
> }
> for(int i=1;i<n;i++)
> {
> int minn=inf;
> int p=-1;
> for(int j=0;j<n;j++)//注意查找最近的村庄
> {
> if(!vis[j]&&minn>low[j])
> {
> minn=low[j];//查找一个更近的后到后更新
> p=j;
> }
> }
> if(minn==inf)
> return -1;
> ans+=minn;
> vis[p]=true;
> for(int j=0;j<n;j++)//结束一轮查找后更新low数组
> {
> if(!vis[j]&&low[j]>cost[p][j])
> low[j]=cost[p][j];
> }
> }
> return ans; }
code:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<string>
#include <set>
using namespace std;
#define ll long long
#define mem(a) memset(a,0,sizeof(a))
const int eps=1e-8;
const int maxn=110;//须填写
const int inf=0x3f3f3f3f;
int vis[maxn];
int low[maxn];
int prim(int cost[][maxn],int n)
{
int ans=0;
mem(vis);
vis[0]=true;
for(int i=1;i<n;i++)
{
low[i]=cost[0][i];
}
for(int i=1;i<n;i++)
{
int minn=inf;
int p=-1;
for(int j=0;j<n;j++)
{
if(!vis[j]&&minn>low[j])
{
minn=low[j];
p=j;
}
}
if(minn==inf)
return -1;
ans+=minn;
vis[p]=true;
for(int j=0;j<n;j++)
{
if(!vis[j]&&low[j]>cost[p][j])
low[j]=cost[p][j];
}
}
return ans;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF&&n)
{
int map[maxn][maxn];
int result=0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
scanf("%d",&map[i][j]);
}
result=prim(map,n);
printf("%d\n",result);
}
return 0;
}