BZOJ1596 [Usaco2008 Jan]电话网络 【树形dp】

题目链接

BZOJ1596

题解

先抽成有根树
\(f[i][0|1][0|1]\)表示以\(i\)为根,儿子都覆盖了,父亲是否覆盖,父亲是否建塔的最少建塔数
转移一下即可

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
using namespace std;
const int maxn = 10005,maxm = 100005,INF = 10000000;
inline int read(){
	int out = 0,flag = 1; char c = getchar();
	while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
	while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
	return out * flag;
}
int f[maxn][2][2],n,fa[maxn];
int h[maxn],ne,de[maxn];
struct EDGE{int to,nxt;}ed[maxn << 1];
inline void build(int u,int v){
	ed[++ne] = (EDGE){v,h[u]}; h[u] = ne;
	ed[++ne] = (EDGE){u,h[v]}; h[v] = ne;
	de[u]++; de[v]++;
}
void dfs(int u){
	f[u][1][1] = 1;
	f[u][0][0] = 0;
	if (u != 1 && de[u] == 1){
		f[u][1][0] = INF;
		return;
	}
	else f[u][1][0] = 0;
	int flag = false;
	Redge(u) if ((to = ed[k].to) != fa[u]){
		fa[to] = u; dfs(to);
		f[u][0][0] += f[to][1][0];
		if (f[to][1][1] <= f[to][1][0]){
			flag = true;
			f[u][1][0] += f[to][1][1];
		}
		else f[u][1][0] += f[to][1][0];
		f[u][1][1] += min(f[to][0][0],min(f[to][1][0],f[to][1][1]));
	}
	if (!flag){
		int mn = INF;
		Redge(u) if ((to = ed[k].to) != fa[u]){
			mn = min(mn,f[to][1][1] - f[to][1][0]);
		}
		f[u][1][0] += mn;
	}
}
int main(){
	n = read();
	for (int i = 1; i < n; i++)
		build(read(),read());
	dfs(1);
	printf("%d\n",min(f[1][1][1],f[1][1][0]));
	return 0;
}

posted @ 2018-05-28 11:48  Mychael  阅读(123)  评论(0编辑  收藏  举报