您的位置:首页 > 其它

Kruskal算法 留给自己进行使用,如有侵权请告知删除

2017-05-03 08:53 120 查看
#include<ostream>
using namespace std;
#include<stdio.h>
#include<queue>
#include<algorithm>
const int maxn=101;
struct edge
{
int from;
int to;
int cost;
friend bool operator <(const edge &e1,const edge &e2)
{
return e1.cost>e2.cost;
}
};
int com(edge e1,edge e2)
{
if(e1<e2)
return 1;
else
return 0;
}
edge reMST[maxn];
int father[maxn];
int nodenum=0,edgenum=0;
int MST;
priority_queue<edge> myQ;

void StoreMap()
{
while(!myQ.empty())
myQ.pop();
for(int i=0;i<nodenum-1;i++)
{
int from,to,cost;
scanf("%d%d%d",&from,&to,&cost);
edge e;
e.from=from;
e.to=to;
e.cost=cost;
myQ.push(e);
}
}

int Find(int x)//每一次进行查找的时候都会进行更新ather[]数组
{
if(x==father[x])
return father[x];
return father[x]=Find(father[x]);
}
bool judge()
{
int f=Find(1);
for(int i=2;i<=nodenum;i++)
{
if(Find(i)!=f)
return false;
}
return true;
}
void print()
{
if(judge())
{
printf("from <-> to  cost:\n");
for(int i=0;i<edgenum-1;i++)
{
printf("%d %d %d\n",reMST[i].from,reMST[i].to,reMST[i].cost);
}
printf("MST is %d",MST);
}
else printf("NO MST exist\n");
}
int kruskal()
{
MST=0;
for(int i=0;i<maxn;i++)//将其每个点都设置为以其序号为root的集合
{
father[i]=i;

}
int num=0;
while(!myQ.empty()&&num!=nodenum-1)
{
edge e=myQ.top();
myQ.pop();
int fx=Find(e.from);//这两步是让其走到最后的那个节点,并且修改其值
int fy=Find(e.to);
if(fx!=fy)
{
father[fx]=fy;
MST+=e.cost;
reMST[num].from=e.from;
reMST[num].to=e.to;
reMST[num].cost=e.cost;
num++;
}
}
return MST;
}
int main()
{
scanf("%d%d",&edgenum,&nodenum);
StoreMap();
kruskal();
print();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kruskal
相关文章推荐