BZOJ P1060 [ZJOI2007]時態同步【樹形DP】
阿新 • • 發佈:2018-12-12
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define ll long long #define rep(i,x,y) for(ll i=(x);i<=(y);i++) #define repl(i,x,y) for(ll i=(x);i<(y);i++) #define repd(i,x,y) for(ll i=(x);i>=(y);i--) using namespace std; const ll N=5e5+5; const ll Inf=1e18; ll n,m,ans,f[N]; ll cnt,to[N<<1],edge[N<<1],nxt[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,ll fa) { for(ll i=head[x];i;i=nxt[i]) if(to[i]!=fa) dfs(to[i],x),f[x]=max(f[x],f[to[i]]+edge[i]); for(ll i=head[x];i;i=nxt[i]) if(to[i]!=fa) ans+=f[x]-f[to[i]]-edge[i]; } int main() { n=read(),m=read(); repl(i,1,n) { ll x=read(),y=read(),z=read(); ins(x,y,z);ins(y,x,z); } dfs(m,0); printf("%lld",ans); return 0; }