HDU 1162 Eddy's picture Kruskal算法
2012-09-05 19:52
134 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1162
题意:
给出N个坐标,坐标之间的距离就是权值,是个最小生成树的问题,用Kruskal算法做。
坑爹:
一道简单的最小生成树的题目,N个点对应要有N-1条边,没什么难点主要是要细心点就行了。
解法:
Kruskal算法的模版一套上去就行了。
View Code
题意:
给出N个坐标,坐标之间的距离就是权值,是个最小生成树的问题,用Kruskal算法做。
坑爹:
一道简单的最小生成树的题目,N个点对应要有N-1条边,没什么难点主要是要细心点就行了。
解法:
Kruskal算法的模版一套上去就行了。
View Code
#include<iostream> #include<math.h> #include<algorithm> using namespace std; const int maxn = 10000 +10; struct edge { int start; int end; double valve; friend bool operator < (struct edge a,struct edge b) { return a.valve<b.valve; } }; struct edge num[maxn]; int father[maxn]; int rank[maxn]; int n; int k; void Make_Set(int x) { father[x] = x ; rank[x] = 0 ; } int find_root(int x) { /*if( father[x]!=x){ return father[x] = find_root(father[x]); } return father[x];*/ if(father[x] == x) { return x; } else { return father[x] = find_root(father[x]); } } void Union(int a,int b) { int roota; int rootb; roota = find_root(a) ; rootb = find_root(b) ; if(roota == rootb ) { return; } if(rank[roota] > rank[rootb] ) { father[rootb] = roota; } else if(rank[roota] < rank[rootb] ) { father[roota] = rootb; } else { father[roota] = rootb; rank[rootb] ++; } } double kruskal() { double sum=0; int count=0; int i; sort(num,num+k); for(i=0; i<k && count<=n-1; i++) { int a; int b; a=num[i].start; b=num[i].end; if(find_root(a)!=find_root(b)) { Union(a,b); sum+=num[i].valve; count++; } } return sum; } int main() { while(cin>>n) { int i; for(i=0; i<maxn; i++) { Make_Set(i); } double a[maxn]; double b[maxn]; for(i=0; i<n; i++) { cin>>a[i]>>b[i]; } int j; k=0; for(i=0; i<n; i++) { for(j=i+1; j<n; j++) { num[k].start=i; num[k].end=j; num[k++].valve = sqrt( (a[j]-a[i])*(a[j]-a[i]) + (b[j]-b[i])*(b[j]-b[i]) ); } } printf("%.2lf\n",kruskal()); } return 0; }
相关文章推荐
- hdu 1162 Eddy's picture
- hdu1162——初学最小生成树
- Hdu-1162 Eddy's picture
- HDU 1162 Eddy's picture
- HDU 1162 Eddy's picture
- HDU-1162-Eddy's picture
- HDU 1162 Eddy's picture【最小生成树,Prime算法+Kruskal算法】
- HDU 1162 prime+邻接矩阵
- 杭电Hdu 1162 Eddy's picture
- HDU 1162 Eddy's picture(图论-最小生成树)
- 最小生成树(模板题)Eddy's picture HDU - 1162
- HDU 1162 Eddy's picture(最小生成树)
- HDU 1162 Eddy's picture 最小生成树
- hdu-1162-Eddy's picture
- HDU 1162 Eddy's picture(点连通:最小生成树)
- hdu 1162 Eddy's picture(最小生成树)
- HDU 1162 Eddy's picture(MST)
- hdu 1162
- hdu 1162 Eddy's picture
- HDU1162-Eddy's picture(最小生成树)