prim算法的前向星实现

#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=100;
const int maxm=maxn*maxn;
struct Edge {
    int from,to,w,next;
};

int n,m;
int pre[maxn];//前向星存储法
Edge e[maxm]; //存储边集
bool vis[maxn]; //判断是否已加入生成树集合
int dis[maxn]; //未确定点集到已确定点集的距离

int main()
{
#ifdef LOCAL_DEBUG
freopen("input.txt","r",stdin);
#endif
    while(~scanf("%d%d",&n,&m) && n+m)
    {
        memset(pre,-1,sizeof(pre));
        memset(vis,0,sizeof(vis));

        //假设无自环
        int from,to,w;
        for(int i=0;i<m;i++) //无向图的存储
        {
            scanf("%d%d%d",&from,&to,&w);
            e[i].from=from; e[i].to=to; e[i].w=w;
            e[i].next=pre[from]; pre[from]=i;
            std::swap(from,to);
            e[i+m].from=from; e[i+m].to=to; e[i+m].w=w;
            e[i+m].next=pre[from]; pre[from]=i+m;
        }

        memset(dis,INF,sizeof(dis));
        dis[1]=0; 
        int ans=0;
        for(int i=0;i<n;i++) //每次确定最小生成树的一个节点,n次确定n个节点
        {
            int minw=INF,v;
            for(int x=1;x<=n;x++) //从候选点集中选择距离已确定点集最短的边
            {
                if(!vis[x] && dis[x]<=minw)
                {
                    minw=dis[x];v=x;
                }
            }
            ans+=minw;
            vis[v]=true; //标记找到的点
            for(int k=pre[v];k!=-1;k=e[k].next) //利用此点更新候选点集各个点到已确定点集的距离
            {
                if(e[k].w<dis[e[k].to] && !vis[e[k].to])
                {
                    dis[e[k].to]=e[k].w;
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值