最小生成树的prim算法实现

#include <iostream>

using namespace std;
const int N=6;
const int data_max=10000000;
struct edge
{
   int point1;
   int point2;
   bool vis;
   int length;//边的长度
}graph_edge[N*(N-1)/2];//用来存放图的边
int edge_num;//边的总数
bool v[N];//记录访问过的顶点
int min_tree[N-1];//记录最小生成树
void prim(int x,int min_tree[])
{
   int i,k=1;
   int min;
   v[x]=true;
   while(k<N)
   {
      min=data_max;
      int t,ed;
      for(i=0;i<edge_num;i++)//寻找一条未标记的权值最小的边
      {
         if(!graph_edge[i].vis)
         {
            if(v[graph_edge[i].point1]&&!v[graph_edge[i].point2])
            {
               if(graph_edge[i].length<min)
               {
                  min=graph_edge[i].length;
                  t=graph_edge[i].point2;
                  ed=i;
               }
            }
            if(!v[graph_edge[i].point1]&&v[graph_edge[i].point2])
            {
                 if(graph_edge[i].length<min)
                 {
                  min=graph_edge[i].length;
                  t=graph_edge[i].point2;
                  ed=i;
                 }
            }
         }
      }
      v[t]=true;
      graph_edge[ed].vis=true;//删除该边
      min_tree[k-1]=ed;
      k++;
   }
}
int main()
{
  freopen("input.txt","r",stdin);
   int m;
   cin>>m;
   edge_num=m;
   int i,x,y,len;
   for(i=0;i<m;i++)//输入图
   {
       cin>>x>>y>>len;
       graph_edge[i].point1=x;
       graph_edge[i].point2=y;
       graph_edge[i].length=len;
       graph_edge[i].vis=false;
   }
   for(i=0;i<N;i++)
      v[i]=false;
   prim(0,min_tree);
   int total_len=0;
   for(i=0;i<N-1;i++)//输出最小生成树
   {
      cout<<graph_edge[min_tree[i]].point1<<" "<<graph_edge[min_tree[i]].point2<<endl;
      total_len+=graph_edge[min_tree[i]].length;
   }
   cout<<total_len<<endl;//输出最小生成树的长度
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值