Tyvj1461

题目链接

分析:
KDtree最远点对

tip

新学的算法就要多加练习
注意:kdtree中的左右儿子不是*2,*2+1这么简单了
一定要调用t[bh].l,t[bh].r
最远距离的计算还是要注意:

这里写图片描述

这里写代码片
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long

using namespace std;

const int N=100010;
struct node{
    ll mx[2],mn[2],d[2],l,r;
};
node t[N];
int n,root,cmpd;
ll x,y;
ll an;

int cmp(const node &a,const node &b)
{
    return (a.d[cmpd]<b.d[cmpd])||((a.d[cmpd]==b.d[cmpd])&&(a.d[!cmpd]<b.d[!cmpd]));
}

ll max(ll a,ll b){if (a>b) return a;else return b;}

void update(int bh)
{
    int lc=t[bh].l;
    int rc=t[bh].r;
    if (lc)
    {
        t[bh].mn[0]=min(t[bh].mn[0],t[lc].mn[0]);
        t[bh].mn[1]=min(t[bh].mn[1],t[lc].mn[1]);
        t[bh].mx[0]=max(t[bh].mx[0],t[lc].mx[0]);
        t[bh].mx[1]=max(t[bh].mx[1],t[lc].mx[1]);
    }
    if (rc)
    {
        t[bh].mn[0]=min(t[bh].mn[0],t[rc].mn[0]);
        t[bh].mn[1]=min(t[bh].mn[1],t[rc].mn[1]);
        t[bh].mx[0]=max(t[bh].mx[0],t[rc].mx[0]);
        t[bh].mx[1]=max(t[bh].mx[1],t[rc].mx[1]);
    }
}

int build(int l,int r,int D)
{
    cmpd=D;
    int mid=(l+r)>>1;
    nth_element(t+1+l,t+1+mid,t+1+r,cmp);
    t[mid].mn[0]=t[mid].mx[0]=t[mid].d[0];
    t[mid].mn[1]=t[mid].mx[1]=t[mid].d[1];
    if (l!=mid) t[mid].l=build(l,mid-1,!D);
    if (r!=mid) t[mid].r=build(mid+1,r,!D);
    update(mid);
    return mid; 
}

ll sqr(ll x){return x*x;}
ll dis(int p,ll x,ll y)
{
    ll d=0;
    d=sqr(max(abs(t[p].mn[0]-x),abs(t[p].mx[0]-x)));
    d+=sqr(max(abs(t[p].mn[1]-y),abs(t[p].mx[1]-y)));
    return d;
}

void ask(int now)
{
    ll d0,dl,dr;
    d0=(x-t[now].d[0])*(x-t[now].d[0])+(y-t[now].d[1])*(y-t[now].d[1]);
    if (t[now].l) dl=dis(t[now].l,x,y);
    else dl=0;
    if (t[now].r) dr=dis(t[now].r,x,y);
    else dr=0;
    if (d0>an) an=d0;
    if (dl>dr)
    {
        if (dl>an) ask(t[now].l);
        if (dr>an) ask(t[now].r);
    }
    else
    {
        if (dr>an) ask(t[now].r);
        if (dl>an) ask(t[now].l); 
    }
}

int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
        scanf("%lld%lld",&t[i].d[0],&t[i].d[1]);
    root=build(1,n,0);
    ll ans=0;
    for (int i=1;i<=n;i++)
    {
        x=t[i].d[0]; y=t[i].d[1];
        an=0;
        ask(root);
        if (an>ans) ans=an;
    }
    printf("%lld",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值