結果
問題 | No.386 貪欲な領主 |
ユーザー |
![]() |
提出日時 | 2016-07-01 23:41:15 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 184 ms / 2,000 ms |
コード長 | 2,509 bytes |
コンパイル時間 | 1,622 ms |
コンパイル使用メモリ | 171,956 KB |
実行使用メモリ | 23,296 KB |
最終ジャッジ日時 | 2024-10-12 19:09:48 |
合計ジャッジ時間 | 3,158 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 16 |
ソースコード
#include <bits/stdc++.h>using namespace std;typedef vector<int> VI;typedef vector<VI> VVI;typedef vector<string> VS;typedef pair<int, int> PII;typedef long long LL;typedef pair<LL, LL> PLL;#define ALL(a) (a).begin(),(a).end()#define RALL(a) (a).rbegin(), (a).rend()#define PB push_back#define EB emplace_back#define MP make_pair#define SZ(a) int((a).size())#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)#define EXIST(s,e) ((s).find(e)!=(s).end())#define SORT(c) sort((c).begin(),(c).end())#define FOR(i,a,b) for(int i=(a);i<(b);++i)#define REP(i,n) FOR(i,0,n)#define FF first#define SS secondtemplate<class S, class T>istream& operator>>(istream& is, pair<S,T>& p){return is >> p.FF >> p.SS;}const double EPS = 1e-10;const double PI = acos(-1.0);const LL MOD = 1e9+7;struct Edge{int to, cost;Edge(int t, int c): to(t), cost(c){}bool operator>(const Edge& rhs) const{return cost > rhs.cost;}bool operator<(const Edge& rhs) const{return cost < rhs.cost;}};typedef vector< vector<Edge> > Graph;// calc Lowest Common Ancestor// O(N logN)int N;const int MAX = 1<<17;const int LOG_MAX = 18;int depth[MAX];int parent[LOG_MAX][MAX];Graph G(MAX);LL cost[MAX];LL sumcost[MAX];void dfs(int node, int p = -1, int d = 0){if(depth[node] >= 0) return;depth[node] = d;parent[0][node] = p;sumcost[node] = (p>=0?sumcost[p]:0) + cost[node];for(int i=0;i<SZ(G[node]);++i)dfs(G[node][i].to, node, d+1);}void init(){fill(depth, depth+MAX, -1);dfs(0);for(int i=0;i+1<LOG_MAX;++i){for(int v=0;v<N;++v){if(parent[i][v] == -1) parent[i+1][v] = -1;else parent[i+1][v] = parent[i][parent[i][v]];}}}int LCA(int u, int v){if(depth[u] > depth[v]) swap(u, v);//depth[u] <= depth[v]for(int i=0;i<LOG_MAX;++i)if((depth[v] - depth[u]) >> i & 1)v = parent[i][v];if(u == v) return u;for(int i=LOG_MAX-1;i>=0;--i){if(parent[i][u] != parent[i][v]){u = parent[i][u];v = parent[i][v];}}return parent[0][u];}int main(){cin.tie(0);ios_base::sync_with_stdio(false);cin >> N;REP(i,N-1){int u, v; cin >> u >> v;G[u].EB(v,1);G[v].EB(u,1);}REP(i,N) cin >> cost[i];init();int M; cin >> M;LL ans = 0;REP(i,M){int a, b, c; cin >> a >> b >> c;if(a == b){ans += c * cost[a];continue;}int u = LCA(a,b);ans += c*(sumcost[a] + sumcost[b] - sumcost[u]*2 + cost[u]);}cout << ans << endl;return 0;}