[POJ2114]Boatherds(点分治+二分)

题目描述

传送门
题意:一棵树,每一次询问树上是否存在两个点距离为x

题解

裸的点分治 暴力就行

代码

#include
#include
#include
#include
#include
using namespace std;
#define N 10005

int n,x,y,m,sum,root;
int q[N],ans[N];
int tot,point[N],nxt[N*2],v[N*2],c[N*2];
int size[N],big[N],d[N],deep[N];
bool vis[N];

void clear()
{
    x=y=m=sum=root=0;
    memset(ans,0,sizeof(ans));
    tot=0;memset(point,0,sizeof(point));
    memset(vis,0,sizeof(vis));
}
void add(int x,int y,int z)
{
    ++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=z;
}
void getroot(int x,int fa)
{
    size[x]=1;big[x]=0;
    for (int i=point[x];i;i=nxt[i])
        if (v[i]!=fa&&!vis[v[i]])
        {
            getroot(v[i],x);
            size[x]+=size[v[i]];
            big[x]=max(big[x],size[v[i]]);
        }
    big[x]=max(big[x],sum-size[x]);
    if (big[x]x;
}
void getdeep(int x,int fa)
{
    deep[++deep[0]]=d[x];
    for (int i=point[x];i;i=nxt[i])
        if (v[i]!=fa&&!vis[v[i]])
        {
            d[v[i]]=d[x]+c[i];
            getdeep(v[i],x);
        }
}
int findl(int l,int r,int k)
{
    int ans=0;
    while (l<=r)
    {
        int mid=(l+r)>>1;
        if (deep[mid]==k) ans=mid,r=mid-1;
        else if (deep[mid]1;
        else r=mid-1;
    }
    return ans;
}
int findr(int l,int r,int k)
{
    int ans=-1;
    while (l<=r)
    {
        int mid=(l+r)>>1;
        if (deep[mid]==k) ans=mid,l=mid+1;
        else if (deep[mid]1;
        else r=mid-1;
    }
    return ans;
}
int calc(int x,int now,int k)
{
    d[x]=now;deep[0]=0;
    getdeep(x,0);
    sort(deep+1,deep+deep[0]+1);
    int t=0;
    for (int i=1;i<=deep[0];++i)
    {
        if (deep[i]+deep[i]>k) break;
        int l=findl(i+1,deep[0],k-deep[i]);
        int r=findr(i+1,deep[0],k-deep[i]);
        t+=r-l+1;
    }
    return t;
}
void dfs(int x)
{
    for (int i=1;i<=m;++i)
        ans[i]+=calc(x,0,q[i]);
    vis[x]=1;
    for (int i=point[x];i;i=nxt[i])
        if (!vis[v[i]])
        {
            for (int j=1;j<=m;++j)
                ans[j]-=calc(v[i],c[i],q[j]);
            sum=size[v[i]];root=0;
            getroot(v[i],0);
            dfs(root);
        }
}

int main()
{
    while (~scanf("%d",&n))
    {
        if (!n) break;
        clear();
        for (int i=1;i<=n;++i)
        {
            while (~scanf("%d",&x))
            {
                if (!x) break;
                scanf("%d",&y);
                add(i,x,y);add(x,i,y);
            }
        }
        while (~scanf("%d",&x))
        {
            if (!x) break;
            q[++m]=x;
        }
        big[0]=N;
        sum=n;root=0;
        getroot(1,0);
        dfs(root);
        for (int i=1;i<=m;++i)
            if (ans[i]) puts("AYE");
            else puts("NAY");
        puts(".");
    }
}

你可能感兴趣的:(题解,二分,点分治)