标签:
#include<cstdio> #include<iostream> #include<cstring> #include<cstdlib> #include<algorithm> #include<cmath> #include<queue> #include<deque> #include<set> #include<map> #include<ctime> #define LL long long #define inf 0x7fffffff #define N 40010 using namespace std; inline LL read() { LL x=0,f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} return x*f; } struct edge{int to,next,v;}e[10*N]; int head[N],son[N],f[N],d[N],s[N]; int n,k,cnt,root,sum,ans,len; bool vis[N]; inline void ins(int u,int v,int w) { e[++cnt].to=v; e[cnt].v=w; e[cnt].next=head[u]; head[u]=cnt; } inline void insert(int u,int v,int w) { ins(u,v,w); ins(v,u,w); } inline void getroot(int x,int fa) { son[x]=1;f[x]=0; for(int i=head[x];i;i=e[i].next) if (fa!=e[i].to&&!vis[e[i].to]) { getroot(e[i].to,x); son[x]+=son[e[i].to]; f[x]=max(f[x],son[e[i].to]); } f[x]=max(f[x],sum-son[x]); if (f[x]<f[root])root=x; } inline void getd(int x,int fa) { s[++len]=d[x]; for (int i=head[x];i;i=e[i].next) if (!vis[e[i].to]&&fa!=e[i].to) { d[e[i].to]=d[x]+e[i].v; getd(e[i].to,x); } } inline int calc(int x,int v) { d[x]=v;len=0; getd(x,0); sort(s+1,s+len+1); int tt=0,l=1,r=len; while (l<r) { if (s[l]+s[r]<=k)tt+=r-l,l++; else r--; } return tt; } inline void solve(int x) { ans+=calc(x,0);vis[x]=1; for(int i=head[x];i;i=e[i].next) if (!vis[e[i].to]) { ans-=calc(e[i].to,e[i].v); sum=son[e[i].to]; root=0; getroot(e[i].to,0); solve(e[i].to); } } int main() { n=read(); for (int i=1;i<n;i++) { int x=read(),y=read(),z=read(); insert(x,y,z); } k=read(); f[0]=n+1;sum=n; getroot(1,0); solve(root); printf("%d\n",ans); return 0; }
标签:
原文地址:http://www.cnblogs.com/zhber/p/4216230.html