prime算法-最小生成树(模板)

hihocoder1097

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn=1e3+7;
typedef long long ll;
int mat[maxn][maxn],vis[maxn],d[maxn];
int n,End,ans;
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++)
            scanf("%d",&mat[i][j]);//i到j的距离
    }
    memset(d,0x3f3f3f3f,sizeof(d));//初始化
    memset(vis,0,sizeof(vis));
    d[1]=0;//第一个节点置为0
    for(int i=1;i<=n;i++){
        int End=-1;//为了求最小值
        for(int j=1;j<=n;j++){//找出与有效集合距离最小的点
          if(!vis[j]&&(End==-1||d[End]>d[j]))
            End=j;
        }
        ans+=d[End];//距离加上
        vis[End]=1;//标记访问
        for(int j=1;j<=n;j++){//更新其他点到有效集合的距离
            if(!vis[j]&&d[j]>mat[End][j])
                d[j]=mat[End][j];//使得d中代表的就是每个点到达有效集合的最短距离
        }
    }
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/holly_Z_P_F/article/details/81240795