結果
| 問題 |
No.1098 LCAs
|
| コンテスト | |
| ユーザー |
SSRS
|
| 提出日時 | 2020-05-24 19:48:08 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 587 ms / 2,000 ms |
| コード長 | 1,565 bytes |
| コンパイル時間 | 2,005 ms |
| コンパイル使用メモリ | 180,340 KB |
| 実行使用メモリ | 43,036 KB |
| 最終ジャッジ日時 | 2024-11-22 16:20:20 |
| 合計ジャッジ時間 | 10,172 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 28 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
int MAX_N = 200000;
struct unionfind{
vector<int> p;
unionfind(int N){
p = vector<int>(N, -1);
}
int root(int x){
if (p[x] == -1){
return x;
} else {
p[x] = root(p[x]);
return p[x];
}
}
bool same(int x, int y){
return root(x) == root(y);
}
void unite(int x, int y){
x = root(x);
y = root(y);
if (x != y){
p[x] = y;
}
}
};
void dfs(vector<pair<long long, long long>> &dp, vector<vector<int>> &c, int v){
for (int w : c[v]){
dfs(dp, c, w);
dp[v].first += dp[w].first + 1;
dp[v].second += (dp[w].first + 1) * (dp[w].first + 1);
}
return;
}
int main(){
int N;
cin >> N;
assert(1 <= N);
assert(N <= MAX_N);
vector<vector<int>> E(N);
unionfind UF(N);
for (int i = 0; i < N - 1; i++){
int u, v;
cin >> u >> v;
assert(1 <= u);
assert(u <= N);
assert(1 <= v);
assert(v <= N);
u--;
v--;
assert(!UF.same(u, v));
E[u].push_back(v);
E[v].push_back(u);
}
vector<int> p(N, -1);
vector<vector<int>> c(N);
queue<int> Q;
Q.push(0);
while (!Q.empty()){
int v = Q.front();
Q.pop();
for (int w : E[v]){
if (w != p[v]){
c[v].push_back(w);
p[w] = v;
Q.push(w);
}
}
}
vector<pair<long long, long long>> dp(N);
dfs(dp, c, 0);
vector<long long> ans(N);
for (int i = 0; i < N; i++){
ans[i] = (dp[i].first + 1) * (dp[i].first + 1) - dp[i].second;
}
for (int i = 0; i < N; i++){
cout << ans[i] << endl;
}
}
SSRS