結果
| 問題 | No.1769 Don't Stop the Game |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-11-03 13:35:40 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.89.0) |
| 結果 |
AC
|
| 実行時間 | 578 ms / 3,000 ms |
| コード長 | 1,472 bytes |
| 記録 | |
| コンパイル時間 | 1,811 ms |
| コンパイル使用メモリ | 78,712 KB |
| 最終ジャッジ日時 | 2025-01-25 10:54:11 |
|
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 28 |
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:18:21: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
18 | int n; scanf("%d", &n);
| ~~~~~^~~~~~~~~~
main.cpp:22:22: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
22 | scanf("%d%d%d", &a[i], &b[i], &c[i]); a[i]--; b[i]--;
| ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ソースコード
/*
# Algorithm
各頂点 v と、その親 p について次の値を求める。
c[v] := v の部分木にあってかつ xor[p; u] がはじめて 0 になるような u の個数
## Time Comlexity
O(N)
*/
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <unordered_map>
int main() {
int n; scanf("%d", &n);
std::vector<std::vector<int>> g(n);
std::vector<int> a(n - 1), b(n - 1), c(n - 1);
for(int i = 0; i < n - 1; i++) {
scanf("%d%d%d", &a[i], &b[i], &c[i]); a[i]--; b[i]--;
g[a[i]].push_back(i);
g[b[i]].push_back(i);
}
using i64 = long long;
i64 ans = 0;
std::vector<int> x(n), root(n), size(n);
std::vector<i64> count(n);
std::unordered_map<int, i64> count_root; {
std::unordered_map<int, int> map;
auto dfs = [&](auto&& dfs, int v, int par, int xor_val) -> void {
auto [it, _] = map.try_emplace(xor_val, -1);
int tmp = it->second;
if(tmp == -1) count_root[xor_val]++;
else count[tmp]++;
x[v] = xor_val;
root[v] = tmp;
size[v] = 1;
for(int id: g[v]) {
int to = a[id] ^ b[id] ^ v;
if(to == par) continue;
map[xor_val] = to;
dfs(dfs, to, v, xor_val ^ c[id]);
size[v] += size[to];
ans += count[to] * (n - size[to]);
}
map[xor_val] = tmp;
}; dfs(dfs, 0, -1, 0);
}
for(int v = 0; v < n; v++) {
if(root[v] == -1) ans += (count_root[x[v]] - 1) * size[v];
else ans += count[root[v]] * size[v];
}
ans = (i64)n * (n - 1) - ans;
printf("%lld\n", ans);
}