其他分享
首页 > 其他分享> > UVA 12093 保卫Zonk Protecting Zonk (树形dp)

UVA 12093 保卫Zonk Protecting Zonk (树形dp)

作者:互联网

题目链接:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=242&page=show_problem&problem=3245

有些麻烦的树形 \(dp\)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn = 20010;

int n, c1, c2;
int h[maxn], cnt = 0;
struct E{
	int to, next;
}e[maxn<<1];
void add(int u, int v){
	e[++cnt].to = v;
	e[cnt].next = h[u];
	h[u] = cnt;
}

int dp[maxn][2]; // 0: A  1: B
int g[maxn][2]; // 不放 0: uncovered 1: covered 
int f[maxn]; // 儿子随意选 0: 没 B  1: 有 B 

void dfs(int u, int par){
	dp[u][0] = c1, dp[u][1] = c2;
	g[u][0] = 0; 
	f[u] = 0;
	
	for(int i = h[u] ; i != -1 ; i = e[i].next){
		int v = e[i].to;
		if(v == par) continue;
		dfs(v, u);
	}
	
	int flag = 0;
	for(int i = h[u] ; i != -1 ; i = e[i].next){
		int v = e[i].to;
		if(v == par) continue;
		if(dp[v][1] <= dp[v][0] && dp[v][1] <= g[v][0] && dp[v][1] <= g[v][1]){
			flag = 1;
		}
		f[u] += min(min(dp[v][0], dp[v][1]), min(g[v][0], g[v][1]));
		
		g[u][0] += min(g[v][1], dp[v][0]);
		//dp[u][0] += min(min(g[v][0], g[v][1]), min(dp[v][0], dp[v][1]));
		dp[u][1] += min(min(min(g[v][0], g[v][1]), min(dp[v][0], dp[v][1])), f[v]);
	}

	dp[u][0] += f[u];
	if(flag) {
		g[u][1] = min(g[u][1], f[u]);
	} else{
		for(int i = h[u] ; i != -1 ; i = e[i].next){
			int v = e[i].to;
			if(v == par) continue;
			g[u][1] = min(g[u][1], f[u] - min(min(g[v][0], g[v][1]), dp[v][0]) + dp[v][1]);
		}
	}
}

ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }

int main(){
	while(scanf("%d%d%d", &n, &c1, &c2) == 3 && n){
		memset(h, -1, sizeof(h)); cnt = 0;
		
		int u, v;
		for(int i = 1 ; i <= n - 1 ; ++i){
			scanf("%d%d", &u, &v);
			add(u, v); add(v, u);
		}
		
		memset(dp, 0x3f, sizeof(dp)); 
		memset(f, 0x3f, sizeof(f));
		memset(g, 0x3f, sizeof(g));
		dfs(1, 0);
		
		printf("%d\n", min(min(g[1][0], g[1][1]), min(dp[1][1], dp[1][0])));
	}
	return 0;
}

标签:ch,Zonk,long,int,maxn,12093,onlinejudge,dp
来源: https://www.cnblogs.com/tuchen/p/15085063.html