洛谷 P6419 [COCI 2014/2015 #1] Kamp
前言:\(v\) 表示子节点,\(w\) 表示边的值,\(fa\) 表示父节点。因为本人一开始不会,所以看了这个题解所以自己写可能会有点像。(stO奇米dalao)
题解
定义 \(f_u\) 表示从点 \(u\) 出发,再回来,完成 \(u\) 这颗子树的最少时间。那么 \(f_u=\sum f_v+2\times w_{u,v}\)
定义 \(g_u\),这个东西和 \(f\) 的差不多,只不过它是除了 \(u\) 这个子树以外的。那么 \(g_u=f_{fa}-(f_u+2\times w_{u,fa})+2\times w_{u,fa}+g_{fa}=f_{fa}-f_u+g_{fa}\) 这个该咋理解呢,我们可以借助一下 \(f\) 咋求的就行,注意:当 \(u\) 这个子树没有人住的时候,还要再加上 \(2\times w_u\) 因为 \(f_u\) 没有,它还差两条边得加上(因为源代码 \(f\) 没有加上这种子节点)。
定义 \(h_{u,0/1}\) 表示在 \(u\) 子树内到那些要到达的点的最大值/次大值。这个东西预处理就行。
定义 \(up_{u}\) 和 \(h\) 差不多,这个表示不在 \(u\) 子树内的,且是最大值。
那么答案就是 \(g_u+f_u-\max\{up_u,h_{u,0}\}\) 怎么理解呢,当 \(up_u\) 最大时,我们从 \(u\) 出发送完子树,再送非子树,然后不回来了,肯定要不走最大的,因为我们要来回到 \(u\) 节点,\(h_{u,0}\) 同理。
\(\mathscr{Code:}\)
//#define FILE_INPUT
#include <iomanip>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
bool Mbe;
#define rep(i, a, b) for (int i = a, END##i = b; i <= END##i; i++)
#define per(i, a, b) for (int i = a, END##i = b; i >= END##i; i--)
#define DEBUG(x) cerr << #x << " = " << x << '\n'
using LL = long long;
using ULL = unsigned long long;
inline LL read() {
LL s = 0, fu = 1; char ch = getchar();
while (ch < '0' || ch > '9') ch == '-' ? fu = -1 : 0, ch = getchar();
while (ch >= '0' && ch <= '9') s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
return s * fu;
}
const int Mod = 1e9 + 7;
const int Inf = 0x3f3f3f3f;
const LL InfLL = 0x3f3f3f3f3f3f3f3f;
const int N = 5e5 + 10;
int head[N], nxt[N << 1], to[N << 1], w[N << 1], idx;
void add_edge(int a, int b, int c) {
to[++idx] = b, w[idx] = c, nxt[idx] = head[a], head[a] = idx;
}
LL f[N], g[N], h1[N], up[N], n, K, h2[N], sz[N];
bool mp[N];
void dp1(int u, int fa) {
sz[u] = mp[u];
for (int i = head[u]; i; i = nxt[i]) {
int v = to[i];
if (v == fa) continue;
dp1(v, u);
sz[u] += sz[v];
if (sz[v]) {
f[u] += f[v] + 2 * w[i];
int val = w[i] + h1[v];
if (h1[u] <= val) h2[u] = h1[u], h1[u] = val;
else if (h2[u] < val) h2[u] = val;
}
}
}
void dp2(int u, int fa) {
for (int i = head[u]; i; i = nxt[i]) {
int v = to[i];
if (v == fa) continue;
if (K - sz[v]) {
g[v] = g[u] + f[u] - f[v];
if (!sz[v]) g[v] += 2 * w[i];
if (h1[v] + w[i] != h1[u]) up[v] = max(up[u], h1[u]) + w[i];
else up[v] = max(up[u], h2[u]) + w[i];
}
dp2(v, u);
}
}
void Init() {
}
void Solve() {
n = read(), K = read();
rep(i, 1, n - 1) {
int a = read(), b = read(), c = read();
add_edge(a, b, c), add_edge(b, a, c);
}
rep(i, 1, K) mp[read()] = 1;
dp1(1, 0);
dp2(1, 0);
rep(i, 1, n) printf("%ll;d\n", g[i] + f[i] - max(up[i], h1[i]));
}
bool Med;
signed main() {
#ifdef FILE_INPUT
freopen("input.in", "r", stdin);
#endif
int T = 1;
// T = read();
while (T--) {
Init();
Solve();
}
cerr << "Memory: " << fixed << setprecision(3) << (&Mbe - &Med) / 1048576.0 << " MB\n";
cerr << "Time: " << fixed << setprecision(3) << 1e3 * clock() / CLOCKS_PER_SEC << " ms\n";
return 0;
}

浙公网安备 33010602011771号