BZOJ3743【Tree DP】

/* I will wait for you*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <string>
#define make make_pair
#define fi first
#define se second

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;

const int maxn = 1000010;
const int maxm = 1010;
const int maxs = 26;
const int inf = 0x3f3f3f3f;
const int P = 1000000007;
const double error = 1e-9;

inline int read()
{
	int x = 0, f = 1;
	char ch = getchar();
	while (ch <= 47 || ch >= 58)
		f = (ch == 45 ? -1 : 1), ch = getchar();
	while (ch >= 48 && ch <= 57)
		x = x * 10 + ch - 48, ch = getchar();
	return x * f;
}

struct egde
{
	int v, w, next; 
} e[maxn];

int n, m, cnt, head[maxn], size[maxn], in[maxn];
ll dis[maxn], fir[maxn], sec[maxn], thi[maxn];

void insert(int u, int v, int w)
{
	e[cnt] = (egde) {v, w, head[u]}, head[u] = cnt++;
}

void dfs_0(int u, int p)
{
	size[u] = in[u], dis[u] = 0;

	for (int i = head[u]; i != -1; i = e[i].next) {
		int v = e[i].v;
		if (v != p) {
			dfs_0(v, u), size[u] += size[v];
			dis[u] += dis[v];
			if (size[v] >= 1)
				dis[u] += e[i].w;
		}
	}
}

void dfs_1(int u, int p)
{
	for (int i = head[u]; i != -1; i = e[i].next) {
		int v = e[i].v;
		if (v != p) {
			dis[v] = dis[u];
			if (size[v] > 0)
				dis[v] -= e[i].w;
			if (m > size[v])
				dis[v] += e[i].w;
			dfs_1(v, u);
		}
	}
}

void dfs_2(int u, int p)
{
	fir[u] = sec[u] = (in[u] ? 0 : (ll) -inf * inf);

	for (int i = head[u]; i != - 1; i = e[i].next) {
		int v = e[i].v;
		if (v != p) {
			dfs_2(v, u);
			if (fir[v] + e[i].w > fir[u]) {
				sec[u] = fir[u];
				fir[u] = fir[v] + e[i].w;	
			}
			else if (fir[v] + e[i].w > sec[u])
				sec[u] = fir[v] + e[i].w;
		}
	}
}

void dfs_3(int u, int p)
{
	for (int i = head[u]; i != -1; i = e[i].next) {
		int v = e[i].v;
		if (v != p) {
			if (fir[v] + e[i].w != fir[u])
				thi[v] = fir[u] + e[i].w;
			else 
				thi[v] = sec[u] + e[i].w;
			thi[v] = max(thi[v], thi[u] + e[i].w);
			dfs_3(v, u);
		}
	}
}

int main()
{	
	n = read(), m = read();

	memset(head, -1, sizeof head);

	for (int i = 1; i < n; i++) {
		int u = read(), v = read(), w = read();
		insert(u, v, w), insert(v, u, w);
	}

	for (int i = 1; i <= m; i++) {
		int w = read();
		in[w] = 1;
	}

	dfs_0(1, 0), dfs_1(1, 0), dfs_2(1, 0);
	thi[1] = (in[1] ? 0 : (ll) -inf * inf), dfs_3(1, 0);

	for (int i = 1; i <= n; i++)
		printf("%lld\n", dis[i] * 2 - max(thi[i], fir[i]));

	return 0;
}

你可能感兴趣的:(BZOJ3743【Tree DP】)