bzoj1509
树的直径
我先开始以为是个图,想想并不知道什么求图的直径的方法,结果是棵树
那么直觉告诉我们是在直径上面,实际上就是直径+min(i->u,i->v),扫一遍就行了
#include<bits/stdc++.h> using namespace std; const int N = 200010; namespace IO { const int Maxlen = N; char buf[Maxlen], *C = buf; int Len; inline void read_in() { Len = fread(C, 1, Maxlen, stdin); buf[Len] = '\0'; } inline void fread(int &x) { x = 0; int f = 1; while (*C < '0' || '9' < *C) { if(*C == '-') f = -1; ++C; } while ('0' <= *C && *C <= '9') x = (x << 1) + (x << 3) + *C - '0', ++C; x *= f; } inline void read(int &x) { x = 0; int f = 1; char c = getchar(); while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); } while(c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); } x *= f; } inline void read(long long &x) { x = 0; long long f = 1; char c = getchar(); while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); } while(c >= '0' && c <= '9') { x = (x << 1ll) + (x << 3ll) + c - '0'; c = getchar(); } x *= f; } } using namespace IO; struct edge { int to; long long w; edge(int to = 0, long long w = 0) : to(to), w(w) {} }; int n, m, root; long long ans; vector<edge> G[N]; long long f[N], g[N], d[N]; void dfs(int u, int last, long long d[]) { if(d[u] > d[root]) root = u; for(int i = 0; i < G[u].size(); ++i) { edge e = G[u][i]; if(e.to == last) continue; d[e.to] = d[u] + e.w; dfs(e.to, u, d); } } int main() { read(n); read(m); for(int i = 1; i <= m; ++i) { int u, v; long long w; read(u); read(v); read(w); G[u].push_back(edge(v, w)); G[v].push_back(edge(u, w)); } dfs(1, 0, f); int u = root; root = 0; dfs(u, 0, g); long long dis = g[root]; u = root; root = 0; dfs(u, 0, d); for(int i = 1; i <= n; ++i) ans = max(ans, dis + min(d[i], g[i])); printf("%lld\n", ans); return 0; }