最小生成树的prim算法实现

来源:互联网 发布:c语言数据类型长度 编辑:程序博客网 时间:2024/06/03 02:23

#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;
}

原创粉丝点击