~~[题目连接]~~版权缘由就不发了。。c++
给出一棵树,求出任意两点之间指望距离的最大值spa
比较清真的一道题吧。。code
设$f[x]$表示从$x$走到$x$的父亲的指望步数get
$g[x]$表示从父亲走来的指望步数it
$d[x]$表示$x$节点的度数class
不可贵到方程$f[x] = \sum_{to \in son[x]} f[to] + d[x]$while
$g[x] = g[fa[x]] + \sum_{to \in son[fa[x]] \text{且} to \not = x} f[to] + d[fa[x]]$co
最后计算的时候维护向上向下最大值便可push
固然,仔细观察不难发现$f[x]$即为子树中全部节点的度数return
$g[x]$为整棵树中除子树外节点的度数
考虑每条边的贡献后不可贵到
$f[x] = 2 * siz[x] - 1$
$g[x] = 2 * (N - siz[x]) - 1$
#include<bits/stdc++.h> #define chmax(a, b) (a = a > b ? a : b) #define LL long long const int MAXN = 1e5 + 10; inline int read() { char c = getchar(); int x = 0, f = 1; while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();} while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * f; } std::vector<int> v[MAXN]; int N, up[MAXN], down[MAXN], d[MAXN], siz[MAXN], ans, f[MAXN], g[MAXN]; void dfs3(int x, int fa) { siz[x] = 1; for(int i = 0, to; i < v[x].size(); i++) { if((to = v[x][i]) == fa) continue; dfs3(to, x); siz[x] += siz[to]; ans = std::max(ans, std::max(up[x] + g[to] + down[to], down[x] + f[to] + up[to])); chmax(up[x], up[to] + f[to]); chmax(down[x], down[to] + g[to]); // chmax(ans, up[x] + down[x]); } f[x] = (siz[x] << 1) - 1; g[x] = ((N - siz[x]) << 1) - 1; } int main() { N = read(); for(int i = 1; i < N; i++) { int x = read(), y = read(); d[x]++; d[y]++; v[x].push_back(y); v[y].push_back(x); } dfs3(1, 0); printf("%lld", ans); puts(".00000"); return 0; }