首页 > 代码库 > bzoj3011[Usaco2012 Dec]Running Away From the Barn*

bzoj3011[Usaco2012 Dec]Running Away From the Barn*

bzoj3011[Usaco2012 Dec]Running Away From the Barn

题意:

给出以1号点为根的一棵有边权的树,问每个点的子树中与它距离小于l的点有多少个。树的大小≤200000。

题解:

每个节点维护一个带标记可并堆,dfs时对子节点的堆加上当前节点到该子节点的边权,之后令其与当前节点的堆合并。

代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <queue>
 5 #define inc(i,j,k) for(int i=j;i<=k;i++)
 6 #define maxn 200010
 7 #define ll long long
 8 using namespace std;
 9 
10 inline ll read(){
11     char ch=getchar(); ll f=1,x=0;
12     while(ch<0||ch>9){if(ch==-)f=-1; ch=getchar();}
13     while(ch>=0&&ch<=9)x=x*10+ch-0,ch=getchar();
14     return f*x;
15 }
16 int rt[maxn],n,ch[maxn][2],ans[maxn]; ll v[maxn],tg[maxn],l;
17 struct e{int t; ll w; int n;}es[maxn]; int g[maxn],ess;
18 void pushdown(int x){
19     if(tg[x]){
20         if(ch[x][0])v[ch[x][0]]+=tg[x],tg[ch[x][0]]+=tg[x];
21         if(ch[x][1])v[ch[x][1]]+=tg[x],tg[ch[x][1]]+=tg[x];
22         tg[x]=0;
23     }
24 }
25 int merge(int x,int y){
26     if(!x||!y)return x+y; if(v[x]<v[y])swap(x,y); pushdown(x);
27     ch[x][1]=merge(ch[x][1],y); swap(ch[x][0],ch[x][1]); return x;
28 }
29 int pop(int x){
30     pushdown(x); return merge(ch[x][0],ch[x][1]);
31 }
32 void dfs(int x,int fa){
33     for(int i=g[x];i;i=es[i].n)if(es[i].t!=fa){
34         dfs(es[i].t,x); tg[rt[es[i].t]]+=es[i].w; v[rt[es[i].t]]+=es[i].w;
35         rt[x]=merge(rt[x],rt[es[i].t]); ans[x]+=ans[es[i].t];
36     }
37     while(v[rt[x]]>l)rt[x]=pop(rt[x]),ans[x]--;
38 }
39 int main(){
40     n=read(); l=read(); inc(i,2,n){int x=read(); ll y=read(); es[i-1]=(e){i,y,g[x]}; g[x]=i-1;} 
41     inc(i,1,n)rt[i]=i,v[i]=0,tg[i]=0,ans[i]=1,ch[i][0]=ch[i][1]=0; dfs(1,0);
42     inc(i,1,n)printf("%d\n",ans[i]); return 0;
43 }

 

20161025

bzoj3011[Usaco2012 Dec]Running Away From the Barn*