您的位置:首页 > 其它

HDU1875 并查集和最小生成树

2016-02-01 15:09 453 查看


畅通工程再续

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 21762 Accepted Submission(s): 6881



Problem Description

相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现。现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政府决定实现百岛湖的全畅通!经过考察小组RPRush对百岛湖的情况充分了解后,决定在符合条件的小岛间建上桥,所谓符合条件,就是2个小岛之间的距离不能小于10米,也不能大于1000米。当然,为了节省资金,只要求实现任意2个小岛之间有路通即可。其中桥的价格为 100元/米。

Input

输入包括多组数据。输入首先包括一个整数T(T <= 200),代表有T组数据。

每组数据首先是一个整数C(C <= 100),代表小岛的个数,接下来是C组坐标,代表每个小岛的坐标,这些坐标都是 0 <= x, y <= 1000的整数。

Output

每组输入数据输出一行,代表建桥的最小花费,结果保留一位小数。如果无法实现工程以达到全部畅通,输出”oh!”.

Sample Input

2
2
10 10
20 20
3
1 1
2 2
1000 1000


Sample Output

1414.2
oh!


遇到的问题和思路:

这道题目的难点就是在于给出的是坐标,然后两个边之间的cost是长度,然而这个长度是需要自己计算的。

我的方法是用一个二重的for循环O(n*n)的复杂度为10000,也是比较小的。然后暴力枚举出所有的边的cost,然后把它放入struct point 中,剩下的就是单纯的kruskal算法了,只要熟悉就可以了。

给出AC代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<cmath>

using namespace std;

typedef long long ll;
const ll MAX_C = 100 + 50;
const ll MAX_X = 1000 + 50;
ll c, x[MAX_X], y[MAX_X];
struct point{
ll from, to;
double cost;
};
ll par[MAX_C], rank1[MAX_C], count1;
point po[MAX_C * MAX_C];

void init(){
for(int i = 1; i <= c; i++){
par[i] = i;
rank1[i] = 0;
}
}

bool cmp(const point &po1, const point &po2){
return po1.cost < po2.cost;
}

int find(int x){
if(par[x] == x) return x;
return par[x] = find(par[x]);
}

void unite(int x, int y){
x = find(x);
y = find(y);
if(x == y) return ;
if(rank1[y] > rank1[x]){
par[x] = y;
}
else {
par[y] = x;
if(rank1[y] == rank1[x])rank1[x]++;
}
}

bool same(int x, int y){
return find(x) == find(y);
}

void kruskal(){
init();
sort(po + 1, po + count1 +1, cmp);
double res = 0;
ll tally = 0;
for(int i = 1; i <= count1; i++){
point e = po[i];
if(!same(e.from, e.to)){
unite(e.from, e.to);
res += e.cost;
tally++;
}
}
if(tally == c-1)printf("%.1f\n", res * 100);
else printf("oh!\n");
}

int main(){
int t;
scanf("%d", &t);
while(t--){
scanf("%I64d", &c);
for(int i = 1; i <= c; i++){
scanf("%I64d%I64d", &x[i], &y[i]);
}
count1 = 0;
for(int i = 1; i <= c; i++){
for(int j = 1; j <= c; j++){
ll p1 = (x[i] - x[j]) * (x[i] - x[j]);
ll p2 = (y[i] - y[j]) * (y[i] - y[j]);
if(p1 + p2 <= 1000 * 1000 && p1 + p2 >= 100){
count1++;
po[count1].from = i;
po[count1].to = j;
po[count1].cost = sqrt(p1 + p2);
}
}
}
kruskal();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: