题面贼长 题贼简单
修改边权使得所有叶子结点到根的路径长度相同
dfs的时候回溯修改成最大值即可
Code:
1 // luogu-judger-enable-o2 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 #include<cstring> 6 #define inf 2147483647 7 #define rep(i,a,n) for(int i = a;i <= n;i++) 8 #define per(i,n,a) for(int i = n;i >= a;i--) 9 using namespace std; 10 typedef long long ll; 11 int read() { 12 int as = 0,fu = 1; 13 char c = getchar(); 14 while(c<‘0‘||c>‘9‘) { 15 if(c == ‘-‘) fu = -1; 16 c = getchar(); 17 } 18 while(c<=‘9‘&&c>=‘0‘) { 19 as = as * 10 + c - ‘0‘; 20 c = getchar(); 21 } 22 return as * fu; 23 } 24 const int N = 1000005; 25 //head 26 int n,s; 27 int head[N],nxt[N],mo[N],cnt; 28 ll cst[N],stk[N],top,sum; 29 inline void add(int x,int y,ll z) { 30 mo[++cnt] = y; 31 cst[cnt] = z; 32 nxt[cnt] = head[x]; 33 head[x] = cnt; 34 return; 35 } 36 ll dep[N]; 37 38 int dfs(int x,int f) { 39 for(int i = head[x];i;i = nxt[i]) { 40 int sn = mo[i]; 41 if(sn == f)continue; 42 dfs(sn,x); 43 dep[x] = max(dep[sn] + cst[i],dep[x]); 44 } 45 for(int i = head[x];i;i = nxt[i]) { 46 int sn = mo[i]; 47 if(sn == f) continue; 48 sum += dep[x] - dep[sn] - cst[i]; 49 } 50 return dep[x]; 51 } 52 53 54 int main() { 55 n = read(); 56 s = read(); 57 rep(i,1,n-1) { 58 int x = read(); 59 int y = read(); 60 ll z = read(); 61 add(x,y,z); 62 add(y,x,z); 63 } 64 dfs(s,s); 65 printf("%lld\n",sum); 66 return 0; 67 }
原文地址:https://www.cnblogs.com/yuyanjiaB/p/9929766.html
时间: 2024-11-04 10:23:56