将树的一条边移掉,然后将这条边重新连接两棵子树,使新树:两两点对的距离之和最小。
枚举删掉的边,对每种情况都计算一下,然后取最小值。
对于每种情况,假设左子树的两两点对和为S1,右子树为S2,子树结点个数分别为C1,C2,两个子树到树根的距离和分别为R1,R2,当前枚举的边的权值为w,则整棵树的代价为:
两棵子树的点对和+经过当前边的点对和
S1 + S2 + (C1 + C2)*w + C1*R2 + C2*R1
一棵树如果确定的话,S1和S2都是确定的,不确定的是R1和R2,因此只需要求出R1和R2的最小值。
f[i] 表示以i为根,其他所有结点到i的代价和。则R = min(f[i]), S = sigma(f[i]) / 2;
f[i]的值很容易通过两边遍历求出(具体看代码)。
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
#define N 5003
const ll inf = 1ll<<60;
int n, s[N], size;
vector<pii> g[N];
ll d[N], ans, f[N], sum, res, s1, s2, r1, r2, c1, c2;
void dfs1(int now, int fa) {
int u; ll w;
s[now] = 1; f[now] = 0;
for (int i=0; i<g[now].size(); i++)
if ((u = g[now][i].first) != fa) {
dfs1(u, now);
s[now] += s[u];
w = g[now][i].second;
f[now] += f[u] + s[u]*w;
}
}
void dfs2(int now, int fa) {
int u; ll w;
sum += f[now], res = min(res, f[now]);
for (int i=0; i<g[now].size(); i++)
if ((u = g[now][i].first) != fa) {
w = g[now][i].second;
f[u] = f[now] + w*(size-2*s[u]);
dfs2(u, now);
}
}
void work(int now, int fa) {
int u; ll w;
for (int i=0; i<g[now].size(); i++)
if ((u = g[now][i].first) != fa) {
dfs1(u, now); size = c1 = s[u]; sum = 0; res = inf;
dfs2(u, now); s1 = sum/2; r1 = res;
dfs1(now, u); size = c2 = s[now]; sum = 0; res = inf;
dfs2(now, u); s2 = sum/2; r2 = res;
w = g[now][i].second;
ans = min(ans, s1+s2+c1*c2*w+c1*r2+c2*r1);
work(u, now);
}
}
int main() {
scanf("%d", &n);
for (int i=0; i<=n; i++) g[i].clear();
for (int i=1, a, b, c; i<n; i++) {
scanf("%d%d%d", &a, &b, &c);
g[a].push_back(make_pair(b, c));
g[b].push_back(make_pair(a, c));
}
ans = inf;
work(1, 0);
cout << ans << endl;
return 0;
}
分享到:
相关推荐
七彩虹主板 cf-af3-e v18 主板BIOS
CF Tree Clustering and support vector machine on kdd Dataset
CF+ and CompactFlash Specification Revision1.4 <br>The CompactFlash Association (CFA) was established in October 1995 with the premise that CompactFlash (CF) technology would enable the ...
CF卡装备源码.e
我就很服气这么好的工具为啥没人用呢?我就缺个远控工具,各位帮下忙,动动,发财的小手谢谢啦。
一个高防CF登录窗口的易语言源码 高防高防!
CF窗口化源码(可调节大小).e 把CF弄成窗口化你懂得
Sandisk cf卡专用工具修改HD模式,解决无法分区的问题,部分新卡不保证有效,注意软件只支持firmware revision已H开头的卡 sandisk公开提供ATCFWCHG.COM程序 具体如下: 将CF卡通过硬盘盒在电脑上建立分区并格式...
cfmmc.cer这是个登陆cfmmc.com的证书,需在jdk中导下
CF方框透视授权 模块 源码.e.......................................
封包封包封包CF2.7封包CF2.7封包CF2.7封包
\CF_IDE_Exemple\uCOSII_FAT_CF 演示程序所在文件夹 \CF_IDE_Exemple\uCOSII_FAT_CF\arm uC/OS-II ARM7 LPC22xx移植代码 \CF_IDE_Exemple\uCOSII_FAT_CF\SOURCE uC/OS-II V2.52源代码(由于版权原因我们不能...
CF一键搜索基址 易语言源码 绝对无毒
概述应用程序树命令安装 $ go get github.com/morikat/cf-plugin-tree$ cf install-plugin $GOPATH/bin/tree用法 $ cf tree 输出样本 $ cf tree cf-dora|--.bash_logout [0/1905]|--.bashrc|--.profile|--app| |--....
自己写的在vxworks下的cf卡底层驱动,改代码经过产品验证证实可靠性。注意该代码是在cf卡8bit模式下实现的。
CF窗口化CF源码
仿CF官网网站源码
easyImageWIN CF卡备份软件
CF卡接口定义,介绍CF卡各接口的功能和作用,便于了解CF卡的功能
强大的易语言CF(穿越火线)源码+模块