BZOJ 2783 [JLOI2012]樹【倍增一下】
阿新 • • 發佈:2018-12-16
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define db double #define sg string #define ll long long #define rep(i,x,y) for(ll i=(x);i<=(y);i++) #define red(i,x,y) for(ll i=(x);i>=(y);i--) #define res(i,x) for(ll i=head[x];i;i=nxt[i]) using namespace std; const ll N=1e5+5; const ll Inf=1e18; ll n,s,ans,v[N],dis[N],fa[N][21]; ll cnt,to[N<<1],nxt[N<<1],edge[N<<1],head[N]; inline ll read() { ll x=0;char ch=getchar();bool f=0; while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();} return f?-x:x; } void ins(ll x,ll y,ll z) { to[++cnt]=y;edge[cnt]=z;nxt[cnt]=head[x];head[x]=cnt; } void dfs(ll x) { rep(i,1,19) fa[x][i]=fa[fa[x][i-1]][i-1]; res(i,x) { ll y=to[i],z=edge[i]; if(y!=fa[x][0]) { dis[y]=dis[x]+z;fa[y][0]=x;dfs(y); } } } void getans(ll x) { ll tmp=x; red(i,20,0) if(dis[x]-dis[fa[tmp][i]]<=s) tmp=fa[tmp][i]; if (dis[x]-dis[tmp]==s) ans++; res(i,x) getans(to[i]); } void File() { freopen("tree.in","r",stdin); freopen("tree.out","w",stdout); } int main() { // File(); n=read(),s=read(); rep(i,1,n) v[i]=read(); rep(i,2,n) { ll x=read(),y=read();ins(x,y,v[y]); } dis[1]=v[1]; dfs(1); getans(1); printf("%lld\n",ans); return 0; }