# 【BZOJ1604】[Usaco2008 Open]Cow Neighborhoods 奶牛的邻居

## Description

1．两只奶牛的曼哈顿距离不超过C(1≤C≤10^9)，即lXi - xil+IYi - Yil≤C.
2．两只奶牛有共同的邻居．即，存在一只奶牛k，使i与k，j与k均同属一个群．
给出奶牛们的位置，请计算草原上有多少个牛群，以及最大的牛群里有多少奶牛

## Input

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

## 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.

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <utility>
#define mp(A,B)	make_pair(A,B)
using namespace std;
const int maxn=100010;
int n,C,root,sum,ans,tot,pre,nxt;
int f[maxn],siz[maxn],vis[maxn];
typedef pair<int,int> pii;
struct node
{
int x,y;
}p[maxn];
struct treap
{
int key,ch[2];
pii v;
}tr[maxn];
int rd()
{
int ret=0,f=1;	char gc=getchar();
while(gc<'0'||gc>'9')	{if(gc=='-')f=-f;	gc=getchar();}
while(gc>='0'&&gc<='9')	ret=ret*10+gc-'0',gc=getchar();
return ret*f;
}
int find(int x)
{
return (f[x]==x)?x:(f[x]=find(f[x]));
}
bool cmp(node a,node b)
{
return a.x<b.x;
}
void rotate(int &x,int d)
{
int y=tr[x].ch[d];
tr[x].ch[d]=tr[y].ch[d^1],tr[y].ch[d^1]=x,x=y;
}
void insert(int &x,pii y)
{
if(!x)
{
x=++tot,tr[x].v=y,tr[x].ch[0]=tr[x].ch[1]=0,tr[x].key=rand()*rand();
return ;
}
int d=(tr[x].v<y);
insert(tr[x].ch[d],y);
if(tr[tr[x].ch[d]].key>tr[x].key)	rotate(x,d);
}
void del(int &x,pii y)
{
if(tr[x].v==y)
{
if(tr[x].ch[0]*tr[x].ch[1]==0)	x=tr[x].ch[0]^tr[x].ch[1];
else
{
int d=tr[tr[x].ch[0]].key<tr[tr[x].ch[1]].key;
rotate(x,d),del(tr[x].ch[d^1],y);
}
return ;
}
del(tr[x].ch[tr[x].v<y],y);
}
void getpre(int x,int y)
{
if(!x)	return ;
if(tr[x].v.first<=y)	pre=x;
getpre(tr[x].ch[tr[x].v.first<=y],y);
}
void getnxt(int x,int y)
{
if(!x)	return ;
if(tr[x].v.first>=y)	nxt=x;
getnxt(tr[x].ch[tr[x].v.first<y],y);
}
int main()
{
srand(2333666);
n=rd(),C=rd();
int i,j,a,b;
for(i=1;i<=n;i++)	a=rd(),b=rd(),p[i].x=a+b,p[i].y=b-a,f[i]=i,siz[i]=1;
sort(p+1,p+n+1,cmp);
for(i=j=1;i<=n;i++)
{
for(;p[i].x-p[j].x>C;j++)	del(root,mp(p[j].y,j));
pre=0,getpre(root,p[i].y);
if(pre&&p[pre].y>=p[i].y-C)
if(find(pre)!=find(i))	siz[f[i]]+=siz[f[pre]],f[f[pre]]=f[i];
nxt=0,getnxt(root,p[i].y);
if(nxt&&p[nxt].y<=p[i].y+C)
if(find(nxt)!=find(i))	siz[f[i]]+=siz[f[nxt]],f[f[nxt]]=f[i];
insert(root,mp(p[i].y,i));
}
for(i=1;i<=n;i++)	if(find(i)==i)	sum++,ans=max(ans,siz[i]);
printf("%d %d\n",sum,ans);
return 0;
}
posted @ 2017-07-11 09:29  CQzhangyu  阅读(181)  评论(0编辑  收藏  举报