您的位置:首页 > 运维架构

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

2017-03-17 21:43 477 查看

1604: [Usaco2008 Open]Cow Neighborhoods 奶牛的邻居

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 933  Solved: 370

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

HINT

Source

Gold

[Submit][Status][Discuss]

题解:set+并查集

对于一个点来说,只需要连接以他为原点,在他的四个象限中离他的曼哈顿距离最近的点即可

那么设这个点为(x,y),四个象限的曼哈顿距离分别是

(x+y)-(X+Y) 

(x-y)-(X-Y)

(X+Y)-(x+y)

(X-Y)-(x-y)

总结一下上面的四个式子,其实两个点的曼哈顿距离可以写成max{|(x+y)-(X+Y)|,|(x-y)-(X-Y)|}的形式。

把每个点改写成(x+y,x-y)的形式,然后按照第一维排序,维护一个set,保证set中元素的第一维的差<=c并且第二维有序,然后对于每个点在set中查询离他最近的两个(一个大于他,一个小于他),如果第二维的差值<=c,就用并查集合并,对于并查集顺便维护一下size即可。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<set>
#define inf 1000000003
#define N 200030
using namespace std;
int n,m,fa
,cnt
,c;
struct data{
int x,y,id;
data (int X=0,int Y=0,int ID=0) {
x=X,y=Y,id=ID;
}
bool operator <(const data &a) const{
return y<a.y;
}
}a
;
multiset<data> s;
int cmp(data a,data b)
{
return a.x<b.x;
}
int find(int x)
{
if (fa[x]==x) return x;
fa[x]=find(fa[x]);
return fa[x];
}
void Union(int x,int y)
{
int r1=find(x); int r2=find(y);
if (r1!=r2) {
fa[r2]=r1; cnt[r1]+=cnt[r2];
}
}
int main()
{
freopen("a.in","r",stdin);
scanf("%d%d",&n,&c);
for (int i=1;i<=n;i++) {
int x,y; scanf("%d%d",&x,&y);
a[i].x=x+y; a[i].y=x-y; a[i].id=i;
}
sort(a+1,a+n+1,cmp);
s.insert(data(0,inf,0)); s.insert(data(0,-inf,0));
s.insert(a[1]); int now=1;
for (int i=1;i<=n;i++) fa[i]=i,cnt[i]=1;
for (int i=2;i<=n;i++) {
while (a[i].x-a[now].x>c)
s.erase(s.find(a[now])),now++;
data r=*s.lower_bound(a[i]); data l=*--(s.lower_bound(a[i]));
if (r.y-a[i].y<=c&&r.id) Union(r.id,a[i].id);
if (a[i].y-l.y<=c&&l.id) Union(l.id,a[i].id);
s.insert(a[i]);
}
int ans=0,mx=0;
for (int i=1;i<=n;i++)
if (find(i)==i) ans++,mx=max(mx,cnt[i]);
printf("%d %d\n",ans,mx);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐