简单的并查集1073家族

1073 家族

题目描述 Description

若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。 规定:x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。如果x,y是亲戚,那么x的亲戚都是y的亲戚,y的亲戚也都是x的亲戚。

输入描述 Input Description

第一行:三个整数n,m,p,(n<=5000,m<=5000,p<=5000),分别表示有n个人,m个亲戚关系,询问p对亲戚关系。 以下m行:每行两个数Mi,Mj,1<=Mi,Mj<=N,表示Ai

和Bi具有亲戚关系。 接下来p行:每行两个数Pi,Pj,询问Pi和Pj是否具有亲戚关系。

输出描述 Output Description

P行,每行一个’Yes’或’No’。表示第i个询问的答案为“具有”或“不具有”亲戚关系。

样例输入 Sample Input

6 5 3

1 2

1 5

3 4

5 2

1 3

1 4

2 3

5 6

样例输出 Sample Output

Yes

Yes

No

数据范围及提示 Data Size & Hint

n<=5000,m<=5000,p<=5000

分析:简单的并查集,对输入数据进行处理(合并),在对询问的数据查找是否在同一集合。

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

const int maxn = 110;

int father[maxn];

struct Point{
    double x, y;
}point[maxn];

struct Line{
    int p1, p2;
    double len;
    bool operator < (const Line& a) const {//重载操作符
        return len < a.len;
    }
}line[maxn*maxn];

double dist(Point a, Point b){
    return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}

int findfather(int a){//查找
    if(a != father[a])
        father[a] = findfather(father[a]);
    return father[a];
}

bool Union(int a, int b){//合并
    int a_root, b_root;
    a_root = findfather(a);
    b_root = findfather(b);
    if(a_root == b_root)
        return false;
    father[b_root] = a_root;
    return true;
}

int main(){
    int n;
    while(~scanf("%d", &n)){
        double sum = 0.0;
        int k = 0;
        for(int i = 0; i < n; i++)
            scanf("%lf%lf", &point[i].x, &point[i].y);
        for(int i = 0; i < n; i++)//初始化数组
            father[i] = i;
        for(int i = 0; i < n; i++){
            for(int j = i + 1; j < n; j++){
                line[k].p1 = i;
                line[k].p2 = j;
                line[k++].len = dist(point[i], point[j]);
            }
        }
        sort(line, line + k);//贪心思想,排序
        for(int i = 0; i < k; i++)
            if(Union(line[i].p1, line[i].p2))//合并成功,累加距离
                sum += line[i].len;
        printf("%.2lf\n", sum);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值