結果

問題 No.1718 Random Squirrel
ユーザー nok0
提出日時 2021-08-04 11:50:33
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 137 ms / 2,000 ms
コード長 1,976 bytes
コンパイル時間 2,388 ms
コンパイル使用メモリ 207,824 KB
最終ジャッジ日時 2025-01-23 14:01:47
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 31
権限があれば一括ダウンロードができます

ソースコード

diff #
プレゼンテーションモードにする

#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<vector<int>> g(n), h(n);
for(int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
--u, --v;
g[u].emplace_back(v);
g[v].emplace_back(u);
}
vector<bool> has_acorn(n);
int root = -1;
for(int i = 0; i < k; i++) {
int a;
cin >> a;
has_acorn[--a] = 1;
root = a;
}
vector<bool> in_tree(n);
auto dfs = [&](auto dfs, int now, int per) -> bool {
bool f = has_acorn[now];
for(auto to : g[now]) {
if(to == per) continue;
f |= dfs(dfs, to, now);
}
return in_tree[now] = f;
};
dfs(dfs, root, -1);
int es = 0;
for(int i = 0; i < n; i++) {
for(auto to : g[i]) {
if(in_tree[i] and in_tree[to]) {
es++;
}
}
}
auto height = [&]() -> vector<int> {
auto bfs = [&](int s) {
vector<int> dist(n, 1 << 30);
queue<int> que;
dist[s] = 0;
que.push(s);
while(!que.empty()) {
int now = que.front();
que.pop();
for(auto to : g[now]) {
if(!in_tree[to] or dist[to] != 1 << 30) continue;
dist[to] = dist[now] + 1;
que.push(to);
}
}
return dist;
};
auto vec1 = bfs(root);
int v1 = -1, v2 = -1;
int dia = -1;
for(int i = 0; i < n; i++)
if(dia < vec1[i] and in_tree[i]) dia = vec1[i], v1 = i;
vec1 = bfs(v1);
dia = -1;
for(int i = 0; i < n; i++)
if(dia < vec1[i] and in_tree[i]) dia = vec1[i], v2 = i;
auto vec2 = bfs(v2);
for(int i = 0; i < n; i++)
if(vec1[i] < vec2[i]) vec1[i] = vec2[i];
return vec1;
};
auto hei = height();
vector<int> res(n);
for(int i = 0; i < n; i++) {
if(in_tree[i]) {
res[i] = es - hei[i];
auto dfs = [&](auto dfs, int now, int per, int val) -> void {
res[now] = val;
for(auto to : g[now]) {
if(to == per) continue;
dfs(dfs, to, now, val + 1);
}
};
for(auto to : g[i]) {
if(!in_tree[to]) {
dfs(dfs, to, i, res[i] + 1);
}
}
}
}
for(auto v : res) cout << v << '\n';
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0