結果

問題 No.3222 Let the World Forget Me
ユーザー areik
提出日時 2025-08-01 22:17:41
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 113 ms / 2,000 ms
コード長 2,190 bytes
コンパイル時間 4,525 ms
コンパイル使用メモリ 269,076 KB
実行使用メモリ 15,488 KB
最終ジャッジ日時 2025-08-01 22:17:50
合計ジャッジ時間 8,034 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 31
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#include <atcoder/all>
using namespace std;

using i32 = int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
using f64 = long double;
using p2 = pair<i64, i64>;
using el = tuple<i64, i64, i64>;
using mint = atcoder::modint998244353;

void _main();
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  _main();
}

i128 pow(i128 x, i128 n) {
  i64 res = 1;
  i64 t = x;
  while (n > 0) {
    if (n & 1) {
      res = res * t;
    }
    t = t * t;
    n >>= 1;
  }
  return res;
}
i64 pow(i64 x, i64 n, i64 m) {
  i64 res = 1;
  i64 t = x % m;
  while (n > 0) {
    if (n & 1) {
      res = res * t % m;
    }
    t = t * t % m;
    n >>= 1;
  }
  return res;
}

void _main() {
  i64 n, m;
  cin >> n >> m;
  vector<i64> p(n);
  vector<vector<i64>> g(n);
  vector<i64> cnt(n, 0);
  for (i64 i = 0; i < n; i++) {
    cin >> p[i];
  }
  for (i64 i = 0; i < n - 1; i++) {
    i64 a, b;
    cin >> a >> b;
    a--, b--;
    g[a].push_back(b);
    g[b].push_back(a);
    cnt[a]++, cnt[b]++;
  }
  vector<i64> dist(n, 1e18);
  queue<i64> que;
  for (i64 i = 0; i < m; i++) {
    i64 c;
    cin >> c;
    c--;
    dist[c] = 0;
    que.push(c);
  }
  while (!que.empty()) {
    i64 i = que.front();
    que.pop();
    for (i64 ni : g[i]) {
      if (dist[ni] > dist[i] + 1) {
        dist[ni] = dist[i] + 1;
        que.push(ni);
      }
    }
  }
  vector<bool> used(n, false);
  vector<p2> ev;
  set<p2> st;
  for (i64 i = 0; i < n; i++) {
    ev.push_back({dist[i], i});
    if (cnt[i] == 1) {
      st.insert({p[i], i});
    }
  }
  sort(ev.begin(), ev.end());
  i64 now = 0;
  i64 idx = 0;
  i64 ans = 0;
  while (!st.empty()) {
    while (idx < ev.size() && ev[idx].first == now) {
      auto [x, i] = ev[idx];
      used[i] = true;
      idx++;
    }
    while (!st.empty() && used[prev(st.end())->second]) {
      st.erase(*prev(st.end()));
    }
    if (st.empty()) break;
    auto [x, i] = *prev(st.end());
    st.erase({x, i});
    if (cnt[i] != 1) break;
    ans += x;
    for (i64 ni : g[i]) {
      cnt[ni]--;
      if (cnt[ni] == 1) {
        st.insert({p[ni], ni});
      }
    }
    now++;
  }
  cout << ans << "\n";
}
0