P3565 POI2014 HOT-Hotels

Description

有一个树形结构,每条边的长度相同,任意两个节点可以相互到达。选3个点。两两距离相等。有多少种方案?

Solution

正确姿势是树形dp加长链剖分.
我写了个暴力…其实这个题有加强版

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
#include <string.h>
#include <algorithm>
const int N = 5005;
const int inf = 0x3f3f3f3f;
int Max;
int dep[N], siz[N];
long long s1[N], s2[N];
struct Edge{
int v,nxt;
}e[N << 1];
int head[N], tot;
void AddEdge(int u,int v) {
e[++tot] = (Edge) {v, head[u]}; head[u] = tot;
e[++tot] = (Edge) {u, head[v]}; head[v] = tot;
}
void dfs(int x,int fa) {
Max = std:: max(dep[x], Max);
siz[dep[x]] += 1;
for (int i = head[x]; i; i = e[i].nxt) if(e[i].v != fa)
dep[e[i].v] = dep[x] + 1, dfs(e[i].v, x);
}
int main() {
int n;
scanf("%d", &n);
for (int i = 1, u, v; i < n; i += 1) {
scanf("%d%d", &u, &v);
AddEdge(u, v);
}
long long ans = 0;
for (int x = 1; x <= n; x += 1) {
memset(s1, 0, sizeof s1);
memset(s2, 0, sizeof s2);
for (int i = head[x]; i; i = e[i].nxt) {
dep[e[i].v] = 1;
dfs(e[i].v, x);
for(int j = 1; j <= Max; j += 1) {
ans += s2[j] * siz[j];
s2[j] += siz[j] * s1[j];
s1[j] += siz[j];
}
for(int j = 1; j <= Max; j += 1) siz[j] = 0;
}
}
printf("%lld\n", ans);
return 0;
}
-------------本文结束感谢您的阅读-------------