[bzoj 1060][luogu p1131]時態同步
阿新 • • 發佈:2017-10-06
bsp getch val pri ges 題目 pre wid http
(似乎是)第一次做樹形DP吔,好雞凍~
題目大意:
一棵有根邊權樹,修改邊權值代價為邊權值變化量,目標狀態是每個葉子到根的路徑權值相等.求達到目標狀態耗費的最小代價.
要把每條路徑的權值加到最大權值,可以證明它最優然而我不會,遞歸處理子樹即可.
代碼如下:
1 #include <cstdio> 2 #include <cstring> 3 #define max(a,b) (((a) > (b)) ? (a) : (b)) 4 #define mcl(a) memset(a,0,sizeof(a)) 5 const int MAXS = 60* 1024 * 1024,N = 500005; 6 inline char __getchar() 7 { 8 static char buf[MAXS];static int len = 0,pos = 0; 9 if(pos == len)pos = 0,len = fread(buf,1,MAXS,stdin);if(pos == len)return ‘\0‘;return buf[pos++]; 10 } 11 inline int getint() 12 { 13 int register num = 0;char register ch = __getchar();for(;ch < ‘0‘ || ch > ‘9‘;ch = __getchar()); 14 for(;ch >= ‘0‘ && ch <= ‘9‘;ch = __getchar())num = (num << 3) + (num << 1) + (ch ^ ‘0‘);return num; 15 } 16 int n,s,cnt = 0,head[N];long long f[N],ans; 17 struct edge{int next,to,val;}e[N << 1]; 18 void addedge(int u,intv,int w){e[++cnt].to = v;e[cnt].next = head[u];head[u] = cnt;e[cnt].val = w;} 19 void dfs(int u,int fa) 20 { 21 for(int register i = head[u];i;i = e[i].next) 22 { 23 int register v = e[i].to;if(v == fa)continue; 24 dfs(v,u); 25 f[u] = max(f[u],f[v] + e[i].val); 26 } 27 for(int register i = head[u];i;i = e[i].next) if(fa != e[i].to) ans += f[u] - f[e[i].to] - e[i].val; 28 } 29 int main() 30 { 31 mcl(head);mcl(e);mcl(f); 32 n = getint();s = getint(); 33 for(int register i = 1;i < n;i++){int register a,b,t;a = getint();b = getint();t = getint();addedge(a,b,t);addedge(b,a,t);} 34 dfs(s,0);printf("%lld\n",ans); 35 return 0; 36 }
用了讀優之後神清氣爽,
BZOJ上432ms Rk15,luogu上48ms Rk 3.
(辣雞B(婊)Z(子)O(口)J(丁))
[bzoj 1060][luogu p1131]時態同步