2018广西省赛.GXBalloons(并查集)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/XxxxxM1/article/details/82255383

问题 G: GXBalloons

时间限制: 1 Sec  内存限制: 128 MB
提交: 77  解决: 28
[提交] [状态] [讨论版] [命题人:admin]

题目描述

The competition is going. Besides the players, volunteers are busy too, they need to send colorful balloons to the contestants. It is known that the contestants are in a huge room of cartesian coordinate system whose seats are 1000 rows multiplying 1000 columns. Every seat could be empty or corresponds to a team. For every minute, volunteers should send all the balloons together. The volunteers will be told where to send each balloon to. They would like to work efficiently. For two positions (r1, c1) and (r2, c2), if the absolute value of (x1 - x2) is not bigger than k or the absolute value of (y1 – y2) is not bigger than k, the two balloons will be sent by a same volunteer. Could you decide how many volunteers are needed at least to send all the balloons?

输入

The first line is an integer T which indicates the case number.
And as for each case, there will be n + 1 lines.
In the first line, there are 2 integers n k, which indicates the number of balloons and the value k.
Then there will be n lines, in every line, there are 2 integers r c which means this balloon will be sent to the r-th row and the c-th column. Please notice that the position could be the same.
It is guaranteed that——
T is about 100.
for 100% cases, 1 <= n <= 10000, 
1 <= k, r, c<= 1000.

输出

As for each case, you need to output a single line.
There should be one integer in the line which means the minimum volunteers are needed.

样例输入

2
3 5
1 1
10 6
15 20
2 5
1 1
7 7

样例输出

1
2

解题思路:并查集模板题

#include<bits/stdc++.h>
using namespace std;
#define maxn 10010
int fa[maxn];
struct node{
    int x,y,d;
}a[maxn];
int get(int x){
    if(x==fa[x]) return x;
    return fa[x]=get(fa[x]);
}
void merge(int x,int y){
    fa[get(x)]=get(y);
}
bool cmp1(node a,node b){
    return a.x<b.x;
}
bool cmp2(node a,node b){
    return a.y<b.y;
}

int main()
{
    int n,t,m;
    cin>>t;
    while(t--&&cin>>n>>m)
    {
        int ans=0;
        for(int i=0;i<n;i++){
            cin>>a[i].x>>a[i].y;
            a[i].d=i,fa[i]=i;
        }
        sort(a,a+n,cmp1);
        for(int i=1;i<n;i++){
            if(a[i].x-a[i-1].x<=m){
                merge(a[i].d,a[i-1].d);
            }
        }
        sort(a,a+n,cmp2);
        for(int i=1;i<n;i++){
            if(a[i].y-a[i-1].y<=m){
                merge(a[i].d,a[i-1].d);
            }
        }
        for(int i=0;i<n;i++){
            if(i==fa[i]) ans++;
        }
        cout<<ans<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/XxxxxM1/article/details/82255383