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; }
相关文章推荐
- 一个使用GridView显示数据,并且可以进行添加、修改、删除操作的例子
- 使用FSO按文件大小浏览文件目录并进行删除操作
- 使用 SQL Server 2008 数据类型-xml 字段类型参数进行数据的批量选取或删除数据
- C#使用XmlDocument操作XML进行查询、增加、修改、删除、保存应用的实例
- 使用jxl对excel进行修改和删除
- 典型J2EE系统架构图,该图为了自己使用而创建,如有什么不当的地方还请高手们指正,谢谢!
- 使用简单的方法进行批量删除数据
- C#使用XmlDocument操作XML进行查询、增加、修改、删除、保存应用的实例
- 使用 SQL Server 2008 数据类型-xml 字段类型参数进行数据的批量选取或删除数据
- 一步一步教你使用AgileEAS.NET基础类库进行应用开发-基础篇-演示ORM的批量删除与更新
- 使用FSO按文件大小浏览文件目录并进行删除操作
- NET简单的一个画图程序 使用简单 自己可以相关自己的内容进行配置就可以使用了
- 使用自己的 CA 来对Exchange 2003 OWA 进行加密
- = = 开始使用一些知识管理工具对自己的知识进行重新组织...
- 使用 SQL Server 2008 数据类型-xml 字段类型参数进行数据的批量选取或删除数据
- 使用VS2005中的GridView中的CommandField进行删除操作时,如何弹出确认对话框?
- 使用VS2008进行VSTO-Addin实战开发-创建自己的工具栏(二)
- 使用VS2008进行VSTO-Addin实战开发-创建自己的工具栏(二)
- jpa 中@ManyToMany 标签使用后,只对关联表进行删除的写法
- 在自己的工程中使用iconv进行编码转换