您的位置:首页 > 其它

[KD-TREE 堆] BZOJ 4520 [Cqoi2016]K远点对

2016-05-18 18:31 337 查看
题意:k远点对

不难想 用堆维护

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;

inline char nc()
{
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}

inline void read(int &x)
{
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

inline ll sqr(int x){ return (ll)x*x; }

const int N=100005;

int n,D,K;
priority_queue<ll, vector<ll>, greater<ll> > Q;

struct node{
int d[2],mx[2],mn[2],l,r;
node(int x=0,int y=0) { mx[0]=mn[0]=d[0]=x; mx[1]=mn[1]=d[1]=y; l=r=0; }
int& operator[](int x) { return d[x]; }
friend bool operator == (const node &A, const node &B) { return A.d[0]==B.d[0] && A.d[1]==B.d[1]; }
friend bool operator < (const node &A,const node &B) { return A.d[D]<B.d[D]; }
friend ll dist(node A,node B) { return sqr(A[1]-B[1])+sqr(A[0]-B[0]); }
}tmp
;

struct KDT{
node T
,now;
int root;
void update(int x){
int l=T[x].l,r=T[x].r;
for(int i=0;i<2;i++)
{
T[x].mn[i]=T[x].mx[i]=T[x][i];
if(l) T[x].mn[i]=min(T[x].mn[i],T[l].mn[i]),T[x].mx[i]=max(T[x].mx[i],T[l].mx[i]);
if(r) T[x].mn[i]=min(T[x].mn[i],T[r].mn[i]),T[x].mx[i]=max(T[x].mx[i],T[r].mx[i]);
}
}
int Reb(int l,int r,int D){
if (l>r) return 0;
int mid=(l+r)>>1;
::D=D; nth_element(tmp+l,tmp+mid,tmp+r+1);
T[mid]=tmp[mid];
T[mid].l=Reb(l,mid-1,D^1);
T[mid].r=Reb(mid+1,r,D^1);
update(mid); return mid;
}
ll Get(node A){
ll ret=0;
for(int i=0;i<2;i++)
ret+=max(sqr(A.mn[i]-now[i]),sqr(A.mx[i]-now[i]));
return ret;
}
void Que(int x){
ll tmp=dist(T[x],now);
if (tmp>Q.top())
Q.pop(),Q.push(tmp);
int l=T[x].l,r=T[x].r; ll dl=-1LL<<60,dr=-1LL<<60;
if(l) dl=Get(T[l]);
if(r) dr=Get(T[r]);
if(dl>dr){
if(dl>Q.top()) Que(l);
if(dr>Q.top()) Que(r);
}else {
if(dr>Q.top()) Que(r);
if(dl>Q.top()) Que(l);
}
}
}KD;

int x
,y
;

int main()
{
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
read(n); read(K);
for (int i=1;i<=n;i++)
read(x[i]),read(y[i]),tmp[i]=node(x[i],y[i]);
KD.root=KD.Reb(1,n,0);
for (int i=1;i<=K+K;i++) Q.push(0LL);
for (int i=1;i<=n;i++)
{
KD.now=tmp[i];
KD.Que(KD.root);
}
printf("%lld\n",Q.top());
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: