傳送門
BZOJ 1604
題面如下
1604: [Usaco2008 Open]Cow Neighborhoods 奶牛的鄰居
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.
I think
曼哈頓距離是可以化簡的。記兩牛座標:
記
於是我們維護一個Multiset存放距離不超過C的牛編號,並查集合並一下就好了。
Code
#include<cstdio>
#include<algorithm>
#include<set>
using namespace std;
const int sm = 1e5+10;
const int Inf = 1e9+5;
int N,C,mx,tot;
int Fa[sm],Ct[sm];
struct data {
int x,y,id;
bool operator < (const data&a) const {
return y<a.y;
}
}a[sm],l,r;
multiset<data>b;
set<data>:: iterator It;//定義一個迭代器
void read(int &x) {
char ch=getchar();x=0;
while(ch>'9'||ch<'0') ch=getchar();
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
}
int Max(int x,int y) { return x>y?x:y; }
bool cmp(data u,data v) { return u.x<v.x; }
int Find(int x){ return x==Fa[x]?x:Fa[x]=Find(Fa[x]); }
void Union(int x,int y) {
int u=Find(x),v=Find(y);
if(u!=v) Fa[u]=v,Ct[v]+=Ct[u];
}
int main() {
read(N),read(C);
for(int i=1,x,y;i<=N;++i) {
read(x),read(y);
a[i].x=x+y,a[i].y=x-y,a[i].id=i;
Fa[i]=i,Ct[i]=1;
}
sort(a+1,a+N+1,cmp);
int cur=1;
b.insert(a[1]);
b.insert((data){0,-Inf,0});
b.insert((data){0, Inf,0});
for(int i=2;i<=N;++i) {
while(a[i].x-a[cur].x>C)
b.erase(b.find(a[cur++]));
It=b.lower_bound(a[i]);//返回第一個大於等於a[i]的迭代器
r=*It,l=*--It;
if(a[i].y-l.y<=C&&l.id) Union(l.id,a[i].id);
if(r.y-a[i].y<=C&&r.id) Union(r.id,a[i].id);
b.insert(a[i]);
}
for(int i=1;i<=N;++i)
if(Find(i)==i) ++tot,mx=Max(mx,Ct[i]);
printf("%d %d\n",tot,mx);
return 0;
}