【BZOJ1131】[POI2008]Sta【TreeDP】

【题目链接】

经典TreeDP。

/* Pigonometry */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 1000005;

int n, head[maxn], cnt, ans, size[maxn];
LL sum;

struct _edge {
	int v, next;
} g[maxn << 1];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v) {
	g[cnt] = (_edge){v, head[u]};
	head[u] = cnt++;
}

inline LL dfs(int x, int f) {
	LL res = 1;
	size[x] = 1;
	for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ f) {
		res += dfs(g[i].v, x) + size[g[i].v];
		size[x] += size[g[i].v];
	}
	return res;
}

inline void dfs2(int x, int f, LL d) {
	if(d > sum || (d == sum && x < ans)) sum = d, ans = x;
	for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ f)
		dfs2(g[i].v, x, d + n - size[g[i].v] * 2);
}

int main() {
	n = iread();
	for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0;

	for(int i = 1; i < n; i++) {
		int u = iread(), v = iread();
		add(u, v); add(v, u);
	}

	sum = dfs(ans = 1, 0);
	dfs2(1, 0, sum);

	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(【BZOJ1131】[POI2008]Sta【TreeDP】)