您的位置:首页 > 其它

uva 10034(最小生成树)

2013-11-24 23:11 369 查看
记得在哪里做过一遍,最简单的最小生成树,直接用kruskal秒掉了。

代码如下:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define LEN 110
using namespace std;

typedef struct {
double x, y;
}POINT;

POINT Point[LEN];

typedef struct {
int a, b;
double w;
}ARC;

ARC Arc[LEN*LEN];
int top, n;

inline double dis(POINT a, POINT b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

//UFSet
int parent[LEN];

void init(){
for(int i=0; i<LEN; i++)parent[i] = i;
}

int Find(int x){
return parent[x]==x?x:parent[x]=Find(parent[x]);
}

void Union(int a, int b){
int pa = Find(a), pb = Find(b);
if(pa!=pb) parent[pa] = pb;
}

//kurskal
bool cmp(ARC a, ARC b){
return a.w<b.w;
}

double kurskal()
{
sort(Arc, Arc+top, cmp);
init();
double ret = 0;
int cnt = 0;
for(int i=0; i<top; i++){
if(cnt == n-1) break;
if(Find(Arc[i].a)!=Find(Arc[i].b)){
cnt++;
Union(Arc[i].a, Arc[i].b);
ret+=Arc[i].w;
}
}
return ret;
}

int main()
{
//    freopen("in.txt", "r", stdin);

int T;
scanf("%d", &T);
while(T--){
scanf("%d", &n);
for(int i=1; i<=n; i++){
scanf("%lf%lf", &Point[i].x, &Point[i].y);
}
top = 0;
for(int i=1; i<=n; i++){
for(int j=i+1; j<=n; j++){
Arc[top].a = i;
Arc[top].b = j;
Arc[top].w = dis(Point[i],Point[j]);
top ++;
}
}
double ans = kurskal();
printf("%.2lf\n", ans);
if(T) printf("\n");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: