結果
問題 | No.386 貪欲な領主 |
ユーザー |
![]() |
提出日時 | 2017-11-23 21:30:32 |
言語 | D (dmd 2.109.1) |
結果 |
AC
|
実行時間 | 449 ms / 2,000 ms |
コード長 | 1,271 bytes |
コンパイル時間 | 599 ms |
コンパイル使用メモリ | 99,708 KB |
実行使用メモリ | 56,368 KB |
最終ジャッジ日時 | 2024-06-12 22:35:16 |
合計ジャッジ時間 | 3,479 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 16 |
ソースコード
void main(){import std.stdio, std.string, std.conv, std.algorithm;int n; rd(n);auto g=new int[][](n, 0);foreach(_; 0..(n-1)){int a, b; rd(a, b);g[a]~=b;g[b]~=a;}auto c=new int[](n);foreach(i; 0..n) rd(c[i]);auto par=new int[][](n, 17);foreach(i; 0..n) fill(par[i], -1);auto cost=new int[](n);auto dep=new int[](n);void dfs(int i, int j=-1, int w=0){par[i][0]=j;cost[i]=w+c[i];if(j>=0) dep[i]=dep[j]+1;foreach(k; g[i]){if(j!=k) dfs(k, i, w+c[i]);}}dfs(0);int getLca(int s, int t){if(dep[s]<dep[t]) swap(s, t);foreach(i; 0..17){if((dep[s]-dep[t])&(1<<i)) s=par[s][i];}if(s==t) return s;for(int i=16; i>=0; i--){if(par[s][i]!=par[t][i]) s=par[s][i], t=par[t][i];}return par[s][0];}for(int j=0; j<16; j++)foreach(i; 0..n){if(par[i][j]>=0) par[i][j+1]=par[par[i][j]][j];}int m; rd(m);long sum=0;while(m--){int a, b, k; rd(a, b, k);auto v=getLca(a, b);sum+=(cost[a]+cost[b]-2*cost[v]+c[v])*k;}writeln(sum);}void rd(T...)(ref T x){import std.stdio, std.string, std.conv;auto l=readln.split;assert(l.length==x.length);foreach(i, ref e; x){e=l[i].to!(typeof(e));}}