BZOJ2820

原题链接

Description

给出n(n5×104)个二维平面上的点,第i个点为(xi,yi),权值为wi。接下来m(m5×104)次询问,给出a,b,c,求所有满足ax+by<c的点的权值和。109a,b,x,y109

Solution

对于这n个点建一棵k-d树,子树维护一个子树和sum
如果子树所代表的矩形的四个顶点都满足ax+by<c,说明子树中的所有点都满足,return sum
如果都不满足ax+by<c,说明子树中的所有点都不满足,就不用做了;
否则就是部分有部分没有,判断当前节点是否满足,然后继续递归下去吧。

Code

//巧克力王国
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long lint;
inline char gc()
{
    static char now[1<<16],*S,*T;
    if(S==T) {T=(S=now)+fread(now,1,1<<16,stdin); if(S==T) return EOF;}
    return *S++;
}
inline int read()
{
    int x=0,f=1; char ch=gc();
    while(ch<'0'||'9'<ch) {if(ch=='-') f=-1; ch=gc();}
    while('0'<=ch&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int const N=1e5+10;
int const INF=0x7FFFFFFF;
int n,m;
#define chL ch[p][0]
#define chR ch[p][1]
int rt,ch[N][2]; lint sum[N];
struct point{int c[2]; lint v;} p1[N],pt[N];
struct zone{int c1[2],c2[2];} zn[N];
int D; bool cmpPt(point x,point y) {return x.c[D]<y.c[D];}
void create(int p,point A)
{
    pt[p]=A;
    for(int k=0;k<2;k++) zn[p].c1[k]=zn[p].c2[k]=A.c[k];
    chL=chR=0; sum[p]=A.v;
}
void update(int p)
{
    for(int k=0;k<2;k++)
    {
        zn[p].c1[k]=min(pt[p].c[k],min(zn[chL].c1[k],zn[chR].c1[k]));
        zn[p].c2[k]=max(pt[p].c[k],max(zn[chL].c2[k],zn[chR].c2[k]));
    }
    sum[p]=pt[p].v+sum[chL]+sum[chR];
}
void build(int &p,int L,int R,int k0)
{
    int mid=L+R>>1; D=k0;
    nth_element(p1+L,p1+mid,p1+R+1,cmpPt);
    create(p=mid,p1[mid]);
    if(L<mid) build(chL,L,mid-1,k0^1);
    if(mid<R) build(chR,mid+1,R,k0^1);
    update(p);
}
lint a,b,c;
bool check(point A) {return A.c[0]*a+A.c[1]*b<c;}
int check(zone z)
{
    int res=0;
    if(z.c1[0]*a+z.c1[1]*b<c) res++;
    if(z.c1[0]*a+z.c2[1]*b<c) res++;
    if(z.c2[0]*a+z.c1[1]*b<c) res++;
    if(z.c2[0]*a+z.c2[1]*b<c) res++;
    return res;
}
lint query(int p)
{
    if(check(zn[p])==4) return sum[p];
    lint res=0;
    if(check(pt[p])) res+=pt[p].v;
    if(chL&&check(zn[chL])) res+=query(chL);
    if(chR&&check(zn[chR])) res+=query(chR);
    return res;
}
int main()
{
    n=read(),m=read();
    for(int k=0;k<2;k++) zn[0].c1[k]=INF,zn[0].c2[k]=-INF;
    for(int i=1;i<=n;i++) p1[i].c[0]=read(),p1[i].c[1]=read(),p1[i].v=read();
    build(rt,1,n,0);
    for(int i=1;i<=m;i++)
    {
        a=read(),b=read(),c=read();
        printf("%lld
",query(rt));
    }
    return 0;
}


P.S.

矩形满足ax+by<c不等价于矩形在直线ax+by=c下方哦,b<0时矩形应该在上方。
要开long long哦。
为什么我的k-d树这么慢啊…时间大概是dalao们的1.5倍以上

原文地址:https://www.cnblogs.com/VisJiao/p/8485746.html