prim最小生成树算法题poj2485
2015-07-28 20:28
363 查看
开始想用kruskal算法自己写写runtime error
#include<cstdio> #include<queue> #include<set> using namespace std; int a[2510][25100]; struct weight { int a,b; int value; bool operator < (const weight & rhs) const { return value < rhs.value; } bool operator > (const weight & rhs) const { return value > rhs.value; } }; int sett[251000]; int find2(int x) { while(x != sett[x]) x=sett[x]; return x; } void merge2(int a,int b) { if(a > b) sett[a]=b; else sett[b]=a; } int main() { int t; scanf("%d",&t); while(t--) { priority_queue<weight , vector<weight> , greater<weight> > pq; int n; scanf("%d",&n); for(int i=0;i<n;i++) sett[i]=i; for(int i=0;i<n;i++) for(int j=0;j<n;j++){ int x; scanf("%d",&x); if(x == 0) x = 65537; weight route; route.a=i; route.b=j; route.value=x; pq.push(route); } set<int> drop; // printf("size=%d n=%d\n",drop.size(),n); while(drop.size() != n-1){ // printf("size=%d n=%d\n",drop.size(),n); weight mi = pq.top(); pq.pop(); int fx =find2(mi.a); int fy =find2(mi.b); if(fx!=fy){ drop.insert(mi.value); merge2(fx,fy); } } // printf("size%d\n",drop.size() ); // for(set<int>::iterator it=drop.begin();it!=drop.end();it++){ // printf("dsa\n"); // printf("%d ",*it); // } set<int>::iterator it = drop.end(); it--; printf("%d\n",*it ); } return 0; } /* 1 4 0 1 2 3 1 0 2 3 2 2 0 3 3 3 3 0 -1073741819 -1073741819 */然后写的prim算法
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; int cost[510][510]; int mincost[510]; bool used[510]; int n; int prim() { memset(used,false,sizeof(used)); memset(mincost,65537,sizeof(mincost)); int MAXres=0; mincost[0]=0; while(true){ int v=-1; for(int i=0;i<n;i++) if(!used[i] && ( v==-1 || mincost[i]<mincost[v]) ) v=i; if(v == -1) break; used[v]=true; if(mincost[v] >MAXres)MAXres=mincost[v]; for(int i=0;i<n;i++) mincost[i] = min(mincost[i], cost[v][i]); } return MAXres; } int main() { int cases; scanf("%d",&cases); while(cases--){ scanf("%d",&n); for(int i=0;i<n;i++) for(int j=0;j<n;j++) { int x; scanf("%d",&cost[i][j]); if(cost[i][j]== 0) cost[i][j] = 65537; } printf("%d\n",prim()); } return 0; }
相关文章推荐
- OpenGL关于glBegin的参数的理解
- I/O复用中,epoll 和select 的区别,以及epoll和select的实例
- 计算机网络读书笔记-----网络层
- Ubuntu 12.04 安装 Apache2+PHP5+MySQL
- 使用 malloc 的一个小问题
- UI__UIGestureRecognize
- 母函数模板解释
- 7.28多校1004——模拟——Painter
- 枚举
- Object类、JAVA反射机制、Annotation功能
- hdu 3635 并查集
- Linux LAMP 搭建
- java基础之集合函数-List
- Snail—UI学习之代理传值Delegate
- makefile 递归用法和.PHONY的讲解
- 单例类Singleton
- Delphi7学习第五天
- 2015年7月28日--博客开通
- linux文本文件查看、显示命令 :cat head tail grep more less nl
- ORACLE-015:ora-25153 临时表空间为空,ora01652 无法通过128