prim 最小生成树
2017-01-30 23:24
375 查看
prim 最小生成树
从单一顶点开始,普里姆算法按照以下步骤逐步扩大树中所含顶点的数目,直到遍及连通图的所有顶点。输入:一个加权连通图,其中顶点集合为V,边集合为E;
初始化:Vnew = {x},其中x为集合V中的任一节点(起始点),Enew = {};
重复下列操作,直到Vnew = V:
在集合E中选取权值最小的边(u, v),其中u为集合Vnew中的元素,而v则是V中没有加入Vnew的顶点(如果存在有多条满足前述条件即具有相同权值的边,则可任意选取其中之一);
将v加入集合Vnew中,将(u, v)加入集合Enew中;
输出:使用集合Vnew和Enew来描述所得到的最小生成树。
使用优先队列优化后复杂度为o(|E|log|V|)。
把33行代码改一下就是Dijkstral了,有木有///
e.from=t,e.to=i,e.val=cost[t 4000 ][i]+val;
传送门》》问题链接
#include<stdio.h> #include<string.h> #include<queue> #include<algorithm> #define INF 0x3f3f3f3f using namespace std; int cost[26][26]; int V; bool used[26]; struct edge{int from,to,val;}e;//val: from 到 to的距离值 bool operator <(edge x,edge y){ return x.val>y.val; } int prim(){ memset(used,0,sizeof(used)); priority_queue<edge> que; cost[0][0]=e.from=e.to=e.val=0; que.push(e); int res=0; while(!que.empty()){ e=que.top();que.pop(); int f=e.from,t=e.to,val=e.val; if(used[t]) continue; used[t]=true; res+=cost[f][t]; // printf("--%c->%c\n",(char)(f+'A'),(char)(t+'A')); for(int i=0;i<26;i++) if(!used[i]&&cost[t][i]!=INF){ e.from=t,e.to=i,e.val=cost[t][i]; que.push(e); } } return res; } int main() { while(~scanf("%d",&V)&&V){ memset(cost,0x3f,sizeof(cost)); int N,val;char a[2],b[2]; for(int i=0;i<V-1;i++){ scanf("%s%d",a,&N); if(N<=0) continue; int x=*a-'A'; while(N--){ scanf("%s%d",b,&val); int y=*b-'A'; cost[x][y]=cost[y][x]=val; } } printf("%d\n",prim()); } return 0; }
相关文章推荐
- Prim最小生成树
- HDU1863 畅通工程 【最小生成树Prim】
- prim 算法 最小生成 树
- 最小生成树之prim模板题
- HDU 1879 还是prim最小生成树、
- POJ 1278 Agri-Net 最小生成树模板题(Prim 与 Kruskal)
- poj 1258 最小生成树 prim
- POJ 1258 Agri-Net (最小生成树+Prim)
- POJ 1258 - Agri-Net(最小生成树' Prim)
- POJ 1789:Truck History(prim&&最小生成树)
- HDU 2489 Minimal Ratio Tree (DFS枚举+最小生成树Prim)
- LA 6437 Power Plant (prim最小生成树)
- POJ 1287 Networking [prim求解最小生成树]
- hdu1162 Eddy's picture 最小生成树 prim
- 最小生成树(Prim)(普利姆最小生成树)
- poj2075(prim()求最小生成树)
- WOJ 656 最小生成树 Prim
- NYOJ38布线问题 prim 最小生成树MST
- HDU 1233 还是畅通工程(最小生成树,prim)
- POJ 1258 Agri-Net (最小生成树 prim)