【bzoj 1604】: [Usaco2008 Open]Cow Neighborhoods 奶牛的邻居 set+并查集

题目http://www.lydsy.com/JudgeOnline/problem.php?id=1604

1604: [Usaco2008 Open]Cow Neighborhoods 奶牛的邻居
Time Limit: 5 Sec Memory Limit: 64 MB
Submit: 783 Solved: 305
[Submit][Status][Discuss]
Description

了解奶牛们的人都知道,奶牛喜欢成群结队.观察约翰的N(1≤N≤100000)只奶牛,你会发现她们已经结成了几个“群”.每只奶牛在吃草的时候有一个独一无二的位置坐标Xi,Yi(l≤Xi,Yi≤[1..10^9];Xi,Yi∈整数.当满足下列两个条件之一,两只奶牛i和j是属于同一个群的:

1.两只奶牛的曼哈顿距离不超过C(1≤C≤10^9),即lXi - xil+IYi - Yil≤C.

2.两只奶牛有共同的邻居.即,存在一只奶牛k,使i与k,j与k均同属一个群.

给出奶牛们的位置,请计算草原上有多少个牛群,以及最大的牛群里有多少奶牛

Input

第1行输入N和C,之后N行每行输入一只奶牛的坐标.

Output

仅一行,先输出牛群数,再输出最大牛群里的牛数,用空格隔开.

Sample Input

4 2

1 1

3 3

2 2

10 10

  • Line 1: A single line with a two space-separated integers: the

    number of cow neighborhoods and the size of the largest cow
    
    neighborhood.
    

Sample Output

2 3

OUTPUT DETAILS:

There are 2 neighborhoods, one formed by the first three cows and

the other being the last cow. The largest neighborhood therefore

has size 3.

思路

!曼哈顿距离=max( |(X+Y)-(x+y)|, |(X-Y)-(x-y)| )

将每个点变为(x+y,x-y)
这样两点的曼哈顿距离就是(|x1 – x2|,|y1 – y2|)

故先按x排序,维护一个队列,满足两两间的x之差《=c;
再在set中找y的前驱与后继,如满足条件则unio做并查集操作,可证明其正确性;

代码

#include<iostream>
#include<stdio.h>
#include<set>
#include<algorithm>
#define N 100005
#define inf 1e16
typedef long long ll;
using namespace std;
struct node{
    ll x,y;
    int id;

}a[N];
int fa[N];
int cnt[N];
int an;
bool operator <(const node a,const node b)
{
    return a.y<b.y;
}
int cmp(node a,node b)
{
    return a.x<b.x;
}
int ans=0;
multiset<node> s;
int n,c;
int find(int x)
{
    if(x==fa[x]) return x;
    return fa[x]=find(fa[x]);
}
void unio(int x,int y)
{
    int pa=find(x);
    int pb=find(y);
    if(pa!=pb)
    {
        ans--;
        fa[pa]=pb;
    }
}
void work()
{
    s.insert(a[1]);
    int now=1;
    node l,r;
    for(int i=2;i<=n;i++)
    {
        while(a[i].x-a[now].x>c) s.erase(s.find(a[now++]));
        set<node>::iterator it=s.lower_bound(a[i]);
        r=*it;
        l=*--it; 
        if (a[i].y-l.y<= c)
        unio(a[i].id,l.id);
        if (r.y-a[i].y<= c)
        unio(a[i].id,r.id);
        s.insert(a[i]);


    }
}
int main()
{
    scanf("%d%d",&n,&c);
    int aa,bb;
    for(int i=1;i<=n;i++)
    {
            scanf("%d%d",&aa,&bb);
            a[i].x=aa+bb;
            a[i].y=aa-bb;
            a[i].id=i;
            fa[i]=i;
    }             
    ans=n;  
    s.insert(node{0,inf,0});
    s.insert(node{0,-inf,0});
    sort(a+1,a+1+n,cmp);       
    work();
    for(int i=1;i<=n;i++)
    {
        cnt[find(i)]++;
    }
    for(int i=1;i<=n;i++)
    {
        an=max(an,cnt[i]);
    }
    printf("%d %d",ans,an);
} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值