結果
| 問題 |
No.1769 Don't Stop the Game
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2025-06-02 17:20:18 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 461 ms / 3,000 ms |
| コード長 | 2,253 bytes |
| コンパイル時間 | 2,313 ms |
| コンパイル使用メモリ | 204,324 KB |
| 実行使用メモリ | 69,376 KB |
| 最終ジャッジ日時 | 2025-06-02 17:20:31 |
| 合計ジャッジ時間 | 12,069 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 28 |
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:92:8: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
92 | scanf("%d", &n);
| ~~~~~^~~~~~~~~~
main.cpp:94:10: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
94 | scanf("%d%d%d", &x, &y, &z);
| ~~~~~^~~~~~~~~~~~~~~~~~~~~~
ソースコード
#include <bits/stdc++.h>
using LL = long long;
const int N = 4e5 + 7;
const int L = 18;
const int MOD = 998244353;
std::vector<std::pair<int, int>> e[N];
std::vector<int> ve[N];
std::pair<int, int> d[N];
int dfn[N], dep[N], sz[N], fa[N][L], cnt;
int a[N], val[N], n, m;
LL ans;
void dfs(int x, int y, int z) {
sz[x] = 1;
dfn[x] = ++cnt;
d[x] = {z, x};
val[x] = z;
for(auto &&[v, w]: e[x])
if(v != y) {
dep[v] = dep[x] + 1;
fa[v][0] = x;
for(int i = 1; i < L; ++i)
fa[v][i] = fa[fa[v][i - 1]][i - 1];
dfs(v, x, z ^ w);
sz[x] += sz[v];
}
}
int lca(int x, int y) {
if(dep[x] < dep[y])
std::swap(x, y);
for(int i = 0; i < L; ++i)
if(dep[x] - dep[y] >> i & 1)
x = fa[x][i];
if(x == y)
return x;
for(int i = L - 1; i >= 0; --i)
if(fa[x][i] != fa[y][i]) {
x = fa[x][i];
y = fa[y][i];
}
return fa[x][0];
}
bool cmp(int x, int y) {
return dfn[x] < dfn[y];
}
void bvt() {
a[++m] = 1;
std::sort(a + 1, a + m + 1, cmp);
for(int i = 2, _i = m; i <= _i; ++i)
a[++m] = lca(a[i - 1], a[i]);
std::sort(a + 1, a + m + 1, cmp);
m = std::unique(a + 1, a + m + 1) - a - 1;
for(int i = 1; i <= m; ++i)
ve[a[i]].clear();
for(int i = 2; i <= m; ++i)
ve[lca(a[i - 1], a[i])].push_back(a[i]);
}
int gdp(int x, int d) {
for(int i = 0; i < L; ++i)
if(dep[x] - d >> i & 1)
x = fa[x][i];
return x;
}
std::pair<int, int> dp(int x, int y) {
if(val[x] == y) {
for(int v: ve[x]) {
auto [c, s] = dp(v, y);
ans -= (1LL * c * (n - sz[gdp(v, dep[x] + 1)]) + s);
}
return {1, sz[x]};
}
int cnt = 0, sz = 0;
for(int v: ve[x]) {
auto [c, s] = dp(v, y);
ans -= (1LL * cnt * s + 1LL * c * sz);
cnt += c;
sz += s;
}
return {cnt, sz};
}
int main() {
scanf("%d", &n);
for(int i = 1, x, y, z; i < n; ++i) {
scanf("%d%d%d", &x, &y, &z);
e[x].push_back({y, z});
e[y].push_back({x, z});
}
ans = 1LL * n * (n - 1);
dfs(1, -1, 0);
std::sort(d + 1, d + n + 1);
for(int i = 1, j; i <= n; i = j) {
m = 0;
for(j = i; j <= n && d[j].first == d[i].first; ++j)
a[++m] = d[j].second;
bvt();
dp(1, d[i].first);
}
printf("%lld\n", ans);
return 0;
}