bzoj 1604: [Usaco2008 Open]Cow Neighborhoods 奶牛的邻居【切比雪夫距离+并查集+multiset】

参考:http://hzwer.com/4361.html
坐标开long long,inf开大点
先曼哈顿转切比雪夫(x+y,x-y),距离就变成了max(x',y');
先按x排序,维护两个指针,指针内区间的x差总是<=c;
用一个multiset维护指针内元素,按y排序,每次加的时候找这个点y的前驱后继,判断是否符合y的差<=c(x已经通过左指针右移eraser完成了),是则加入并查集,像生成树那样的做法;
然后统计一下并查集的根个数和maxsize即可
转切比雪夫是重点!

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<set>
using namespace std;
const int N=100005;
const long long inf=1e15;
int n,m,f[N],c[N],con,mx;
struct qwe
{
    long long x,y;
    int id;
    qwe(long long X=0,long long Y=0,int ID=0)
    {
        x=X,y=Y,id=ID;
    }
    bool operator < (const qwe &a) const
    {
        return y<a.y;
    }
}a[N];
multiset<qwe>s;
bool cmp(const qwe &a,const qwe &b)
{
    return a.x<b.x;
}
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
inline int zhao(int x)
{
    return x==f[x]?x:f[x]=zhao(f[x]);
}
void hb(int x,int y)
{
    int fx=zhao(x),fy=zhao(y);
    if(fx!=fy)
        f[fx]=fy;
}
int main()
{
    n=read(),m=read();
    for(int i=1;i<=n;i++)
    {
        int x=read(),y=read();
        a[i]=qwe(x+y,x-y,i);f[i]=i;
    }
    sort(a+1,a+1+n,cmp);
    s.insert(qwe(0,inf,0));
    s.insert(qwe(0,-inf,0));
    s.insert(a[1]);
    int w=1;
    for(int i=2;i<=n;i++)
    {
        while(a[i].x-a[w].x>m)
            s.erase(s.find(a[w++]));
        multiset<qwe>::iterator it=s.lower_bound(a[i]);
        qwe r=*it,l=*--it;
        if(a[i].y-l.y<=m)
            hb(a[i].id,l.id);
        if(r.y-a[i].y<=m)
            hb(a[i].id,r.id);
        s.insert(a[i]);
    }
    for(int i=1;i<=n;i++)
        c[zhao(i)]++;
    for(int i=1;i<=n;i++)
        if(c[i]>0)
            mx=max(mx,c[i]),con++;
    printf("%d %d\n",con,mx);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lokiii/p/8993622.html