题意:
给一个森林,要你用边权为w的边把森林连成一棵树,问树的最小直径。
做法:
肯定是将每一棵树的中心(直径的中点)连起来。
然后你肯定是连成一个菊花图最优。
并且菊花图最中间那个点肯定要放直径最长的那棵树。
于是答案等于
1.每个树的直径的最大值
2.最大半径+次大半径+w
3.次大半径+第三大半径+w+w
这三种的最大值。
易错点:
保存前三大的时候初始值要赋为-1e18,亲测,-1e9也不行QAQ.
代码:
/*************************************************************
Problem: bzoj 3246 [Ioi2013]Dreaming
User: fengyuan
Language: C++
Result: Accepted
Time: 6656 ms
Memory: 32204 kb
Submit_Time: 2018-01-03 11:37:17
*************************************************************/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const int N = 500010;
int n, m, cnt;
LL w, r, ans;
int head[N], son[N];
LL f[N], g[N];
bool vis[N];
struct Edge{
int to, nex; LL v;
Edge() {}
Edge(int x, int y, LL z) { to = x, nex = y, v = z; }
}e[N<<1];
inline void addEdge(int x, int y, LL z){ e[++ cnt] = Edge(y, head[x], z); head[x] = cnt; }
inline void dfs(int u, int lst)
{
vis[u] = 1; f[u] = g[u] = 0;
for(int i = head[u]; i; i = e[i].nex) {
int v = e[i].to; if(v == lst) continue;
dfs(v, u);
if(f[v]+e[i].v > f[u]) son[u] = v, f[u] = f[v]+e[i].v;
}
for(int i = head[u]; i; i = e[i].nex)
if(e[i].to != lst && e[i].to != son[u]) if(f[e[i].to]+e[i].v > g[u]) g[u] = f[e[i].to]+e[i].v;
}
inline void dfs2(int u, int lst, LL d)
{
if(d > f[u]) g[u] = f[u], f[u] = d, son[u] = lst;
else if(d > g[u]) g[u] = d;
r = min(r, f[u]); ans = max(ans, f[u]);
for(int i = head[u]; i; i = e[i].nex) if(e[i].to != lst) {
if(e[i].to != son[u]) dfs2(e[i].to, u, f[u]+e[i].v);
else dfs2(e[i].to, u, g[u]+e[i].v);
}
}
int main()
{
scanf("%d%d%lld", &n, &m, &w);
for(int i = 1; i <= m; i ++) {
int x, y; LL z; scanf("%d%d%lld", &x, &y, &z);
x ++, y ++; addEdge(x, y, z); addEdge(y, x, z);
}
LL mx = -1e18, mx2 = -1e18, mx3 = -1e18;//这边一定要赋最小,-1e9也没用。
for(int i = 1; i <= n; i ++) if(!vis[i]) {
r = 1e18; dfs(i, 0); dfs2(i, 0, 0);
if(r > mx) mx3 = mx2, mx2 = mx, mx = r;
else if(r > mx2) mx3 = mx2, mx2 = r;
else if(r > mx3) mx3 = r;
}
ans = max(ans, mx+w+mx2);
ans = max(ans, mx2+mx3+w+w);
printf("%lld\n", ans);
return 0;
}