Problem G Balloons(基础并查集)

Problem G Balloons

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 220    Accepted Submission(s): 57

Problem Description
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?
 
Input
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.
 
Output
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.
 
Sample Input
 
  
2 3 5 1 1 10 6 15 20 2 5 1 1 7 7
 
Sample Output
 
  
1 2

【题解】

对不起我也不知道那个时候为什么不写这道题.....可能下意识就觉得难

思路:基础并查集

【代码】

#include<bits/stdc++.h>
using namespace std;
int pre[10005];
struct p{
    int x,y,c;
}f[10005];
int find(int x)
{
    return x==pre[x]?x:pre[x]=find(pre[x]);
}
void join(int x,int y)
{
    x=find(x),y=find(y);
    if(x!=y)
      pre[x]=y;
}
bool cmp1(p a,p b)
{
    return a.x<b.x;
}
bool cmp2(p a,p b)
{
    return a.y<b.y;
}
int main()
{
    int t,n,k,i;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&k);
        for(i=1;i<=n;i++)
        {
            scanf("%d%d",&f[i].x,&f[i].y);
            f[i].c=i;
            pre[i]=i;
        }
        sort(f+1,f+n+1,cmp1);
        for(i=1;i<n;i++)
        {
            if(f[i+1].x-f[i].x<=k)
                join(f[i+1].c,f[i].c);
        }

        sort(f+1,f+n+1,cmp2);
        for(i=1;i<n;i++)
            if(f[i+1].y-f[i].y<=k)
                join(f[i+1].c,f[i].c);
        int ans=0;
        for(i=1;i<=n;i++)
            if(i==pre[i])
               ans++;
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41117236/article/details/81060603