#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;
}
prim算法的前向星实现
最新推荐文章于 2020-06-13 18:20:36 发布