POJ 2114 点分治
思路:
点分治
//By SiriusRen
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 10005
int n,k,xx,yy,first[N],next[N*2],v[N*2],w[N*2],tot;
int f[N],size[N],vis[N],d[N],deep[N],root,sum,ans;
void add(int x,int y,int z){w[tot]=z,v[tot]=y,next[tot]=first[x],first[x]=tot++;}
void getroot(int x,int fa){
size[x]=1,f[x]=0;
for(int i=first[x];~i;i=next[i])if(!vis[v[i]]&&v[i]!=fa)
getroot(v[i],x),size[x]+=size[v[i]],f[x]=max(f[x],size[v[i]]);
f[x]=max(f[x],sum-size[x]);
if(f[x]<f[root])root=x;
}
void getdeep(int x,int fa){
deep[++deep[0]]=d[x];
for(int i=first[x];~i;i=next[i])if(v[i]!=fa&&!vis[v[i]]&&d[x]+w[i]<=k)
d[v[i]]=d[x]+w[i],getdeep(v[i],x);
}
int calc(int x,int now){
d[x]=now,deep[0]=0,getdeep(x,0);
sort(deep+1,deep+deep[0]+1);
int t=0,l=1,r=deep[0];
while(l<r)
if(deep[l]+deep[r]<k)l++;
else if(deep[l]+deep[r]>k)r--;
else{
if(deep[l]==deep[r]){t+=(r-l+1)*(r-l)/2;break;}
int st=l,ed=r;
while(deep[st]==deep[l])st++;
while(deep[ed]==deep[r])ed--;
t+=(st-l)*(r-ed);
l=st,r=ed;
}
return t;
}
void work(int x){
ans+=calc(root,0),vis[x]=1;
for(int i=first[x];~i;i=next[i])if(!vis[v[i]])
ans-=calc(v[i],w[i]),
sum=size[v[i]],root=0,
getroot(v[i],x),work(root);
}
int read(){
int x=0;char p=getchar();
while(p<'0'||p>'9')p=getchar();
while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();
return x;
}
int main(){
while(scanf("%d",&n)&&n){
memset(first,-1,sizeof(first));tot=0;
for(int i=1;i<=n;i++)
while(xx=read())
yy=read(),add(i,xx,yy),add(xx,i,yy);
while(k=read()){
memset(vis,0,sizeof(vis));
f[0]=10005,root=ans=0,sum=n,getroot(1,0);
work(root);
puts(ans?"AYE":"NAY");
}puts(".");
}
}