結果

問題 No.386 貪欲な領主
ユーザー ninja-kidninja-kid
提出日時 2023-02-14 12:11:03
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 253 ms / 2,000 ms
コード長 2,186 bytes
コンパイル時間 4,127 ms
コンパイル使用メモリ 263,216 KB
実行使用メモリ 24,544 KB
最終ジャッジ日時 2023-09-23 23:26:23
合計ジャッジ時間 6,383 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,376 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 253 ms
24,500 KB
testcase_05 AC 222 ms
18,932 KB
testcase_06 AC 222 ms
18,872 KB
testcase_07 AC 3 ms
4,384 KB
testcase_08 AC 30 ms
4,732 KB
testcase_09 AC 5 ms
4,380 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 1 ms
4,380 KB
testcase_12 AC 3 ms
4,380 KB
testcase_13 AC 6 ms
4,380 KB
testcase_14 AC 226 ms
18,928 KB
testcase_15 AC 216 ms
24,544 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#include <atcoder/all>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace atcoder;
using ll = long long;
const ll MOD1 = 1000000007LL;
const ll MOD2 = 998244353LL;
using namespace std;
const vector<pair<int, int>> dpos4 = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
// const vector<pair<int, int>> dpos8 = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};

template <typename T>
bool chmax(T &a, const T& b) {
  if (a < b) {
    a = b;  // aをbで更新
    return true;
  }
  return false;
}
// aよりもbが小さいならばaをbで更新する
// (更新されたならばtrueを返す)
template <typename T>
bool chmin(T &a, const T& b) {
  if (a > b) {
    a = b;  // aをbで更新
    return true;
  }
  return false;
}

int main() {
  int N;
  cin >> N;
  vector<vector<int>> edges(N);
  rep(i, N - 1){
    int a, b; cin >> a >> b;
    edges[a].push_back(b);
    edges[b].push_back(a);
  }
  vector<ll> U(N);
  rep(i, N) cin >> U[i];
  
  vector<int> depth(N, 0);
  vector<ll> money(N, 0);
  vector<vector<int>> parent(20, vector<int>(N, 0));
  
  money[0] = U[0];
  auto dfs = [&](auto self, int fr, int prev=-1) -> void {
    for(auto to: edges[fr]){
      if(to == prev) continue;
      depth[to] = depth[fr] + 1;
      money[to] = money[fr] + U[to];
      parent[0][to] = fr;
      self(self, to, fr);
    }
  };
  
  dfs(dfs, 0);
  
  for(int i = 1; i < 20; i++){
    rep(j, N){
      parent[i][j] = parent[i - 1][parent[i - 1][j]];
    }
  }
  
  auto get_lca = [&](int a, int b) {
    if(depth[a] < depth[b]) swap(a, b);
    int d = depth[a] - depth[b];
    rep(i, 20){
      if((d >> i) % 2 == 1) a = parent[i][a];
    }
    if(a == b) return a;
    for(int i = 19; i >= 0; i--){
      if(parent[i][a] == parent[i][b]) continue;
      a = parent[i][a];
      b = parent[i][b];
    }
    return parent[0][a];
  };
  
  auto calc = [&](int a, int b){
    int p = get_lca(a, b);
    ll ans = money[a] + money[b] - 2 * money[p] + U[p];
    return ans;
  };
  int M;
  cin >> M;
  ll ans = 0;
  rep(i, M){
    int a, b, c;
    cin >> a >> b >> c;
    ans += calc(a, b) * c;
  }
  cout << ans << endl;
  return 0;
}
0