POJ 1251 Jungle Roads(最小生成树)
2016-03-17 18:18
351 查看
题目链接:
POJ 1251 Jungle Roads
题意:
n个点,每个点有m条无向边,每条边有一个权值,求最少的路径权值和使得n个点连通。
分析:
最小生成树裸题。
CODE:
POJ 1251 Jungle Roads
题意:
n个点,每个点有m条无向边,每条边有一个权值,求最少的路径权值和使得n个点连通。
分析:
最小生成树裸题。
CODE:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const int maxn=27; int n,uu,vv,ww,m,ans,tot; int pre[maxn]; char s[5]; struct Edge{ int u,v,w; }edge[maxn*maxn]; bool cmp(struct Edge a,struct Edge b) { return a.w<b.w;//按边权值升序排序 } void init() { tot=0; ans=0; for(int i=0;i<maxn;i++) pre[i]=i; } int find(int x) { return pre[x]==x?x:pre[x]=find(pre[x]); } int main() { #ifdef LOCAL freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); #endif while(~scanf("%d",&n)&&n) { init(); for(int i=1;i<n;i++) { scanf("%s%d",s,&m); uu=s[0]-'A'+1; for(int j=1;j<=m;j++) { scanf("%s%d",s,&ww); edge[tot].u=uu; edge[tot].v=s[0]-'A'+1; edge[tot].w=ww; tot++; } } sort(edge,edge+tot,cmp); //Kruskal Algorithm for(int i=0;i<tot;i++) { uu=edge[i].u; vv=edge[i].v; ww=edge[i].w; int fu=find(uu); int fv=find(vv); if(fu!=fv) { ans+=ww; pre[fu]=fv; } } printf("%d\n",ans); } return 0; }
相关文章推荐
- 详解图的应用(最小生成树、拓扑排序、关键路径、最短路径)
- 最小生成树算法之Prim算法
- 使用C语言实现最小生成树求解的简单方法
- 最小生成树算法——Prim和Kruskal算法的实现
- Data Structure - Week 15
- poj 2485 Highways
- HDU1301 最小生成树kruskal裸题
- Kruskal 最小生成树
- 最小生成树
- 图的最小生成树学习笔记
- 克如斯卡尔算法--最小生成树
- 普里姆算法--最小生成树
- poj2395 解题报告
- HDU-1233 还是畅通工程(最小生成树&并查集)
- 最小生成树之prim算法
- 最小生成树 : Kruskal 算法
- 最小生成树 : Prim 算法
- java数据结构 最小生成树
- POJ1251-Jungle Roads
- POJ1287-Networking