結果
| 問題 |
No.399 動的な領主
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2025-11-11 16:05:05 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 101 ms / 2,000 ms |
| コード長 | 1,340 bytes |
| コンパイル時間 | 1,966 ms |
| コンパイル使用メモリ | 195,120 KB |
| 実行使用メモリ | 30,976 KB |
| 最終ジャッジ日時 | 2025-11-11 16:05:10 |
| 合計ジャッジ時間 | 5,007 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 19 |
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:54:14: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
54 | scanf("%lld", &n);
| ~~~~~^~~~~~~~~~~~
main.cpp:58:22: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
58 | scanf("%lld%lld", &u, &v);
| ~~~~~^~~~~~~~~~~~~~~~~~~~
main.cpp:62:14: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
62 | scanf("%lld", &q);
| ~~~~~^~~~~~~~~~~~
main.cpp:66:22: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
66 | scanf("%lld%lld", &a, &b);
| ~~~~~^~~~~~~~~~~~~~~~~~~~
ソースコード
# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100010;
struct edge {ll to, next;} e[N << 1];
ll n, q, ans;
ll cnt, head[N];
ll dep[N], d[N];
ll f[N][22];
void add(ll u, ll v) {e[++cnt] = {v, head[u]}, head[u] = cnt;}
void DFS(ll u, ll fa)
{
dep[u] = dep[fa] + 1;
f[u][0] = fa;
for (int i = 1; (1 << i) <= dep[u]; i++) f[u][i] = f[f[u][i - 1]][i - 1];
ll v;
for (int i = head[u]; i; i = e[i].next)
{
v = e[i].to;
if (v == fa) continue;
DFS(v, u);
}
}
ll DFS2(ll u, ll fa)
{
ll v;
for (int i = head[u]; i; i = e[i].next)
{
v = e[i].to;
if (v == fa) continue;
d[u] += DFS2(v, u);
}
ans += (d[u] + 1) * d[u] / 2;
return d[u];
}
ll LCA(ll u, ll v)
{
if (dep[u] < dep[v]) swap(u, v);
ll txp;
txp = dep[u] - dep[v];
for (int i = 21; i >= 0; i--) if (txp & (1 << i)) u = f[u][i];
if (u == v) return u;
for (int i = 21; i >= 0; i--) if (f[u][i] != f[v][i]) u = f[u][i], v = f[v][i];
return f[u][0];
}
int main()
{
scanf("%lld", &n);
for (int i = 1; i < n; i++)
{
ll u, v;
scanf("%lld%lld", &u, &v);
add(u, v), add(v, u);
}
DFS(1, 0);
scanf("%lld", &q);
while (q--)
{
ll a, b, lca;
scanf("%lld%lld", &a, &b);
lca = LCA(a, b);
d[a]++, d[b]++;
d[lca]--;
if (f[lca][0] >= 0) d[f[lca][0]]--;
}
ans = 0;
DFS2(1, 0);
printf("%lld\n", ans);
return 0;
}