【BZOJ 1604】Cow Neighborhoods(哈夫曼距离+Multiset)

传送门

    BZOJ 1604
    题面如下

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

Time Limit: 5 Sec Memory Limit: 64 MB

Submit: 1035 Solved: 414

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

    曼哈顿距离是可以化简的。记两牛坐标: (a1,b1),(a2,b2)

Dist=|a1a2|+|b1b2|

Dist=a1a2+b1b2=(a1+b1)(a2+b2)

Dist=a1a2b1+b2=(a1b1)(a2b2)

Dist=a1+a2+b1b2=(a1b1)+(a2b2)

Dist=a1+a2b1+b2=(a1+b1)+(a2+b2)

    记 xi=ai+bi,yi=aibi
Dist=|x1x2|

Dist=|y1y2|

    于是我们维护一个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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值