【POJ3659】Cell Phone Network【树上最小点支配】【TreeDP】

【题目链接】

再写一发。

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

using namespace std;

const int maxn = 10005, inf = 0x3f3f3f3f;

int n, dp[maxn][3], head[maxn], cnt;

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 void dfs(int x, int f) {
	dp[x][0] = 1;
	int del = inf; bool flag = 1; 
	for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ f) {
		int v = g[i].v;
		dfs(v, x);
		dp[x][0] += min(dp[v][0], min(dp[v][1], dp[v][2]));
		dp[x][2] += min(dp[v][0], dp[v][1]);
		if(dp[v][0] <= dp[v][1]) {
			flag = 0;
			dp[x][1] += dp[v][0];
		} else {
			dp[x][1] += dp[v][1];
			del = min(del, dp[v][0] - dp[v][1]);
		}
	}
	if(flag) dp[x][1] += del;
}

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);
	}

	dfs(1, 0);

	printf("%d\n", min(dp[1][0], dp[1][1]));
	return 0;
}


你可能感兴趣的:(【POJ3659】Cell Phone Network【树上最小点支配】【TreeDP】)