POJ 1463 Strategic game 树形dp

http://poj.org/problem?id=1463

题意:选中一个点,则与其相连的边被覆蓋,求最少选多少点使所有点被覆蓋。

每个节点或选或不选,用dp[u][0/1]表示。

初始状态:dp[u][0]=0;dp[u][1]=1;

非叶节点u:若不选,则与子节点的边由子节点覆蓋,dp[u][0] += dp[v][1];

                    若选,则子节点可选可不选,dp[u][1] += min(dp[v][0], dp[v][1])。

最终结果为min(dp[root][0],dp[root][1]).。

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

const int maxn = 1505;
int dp[maxn][2], father[maxn], N;
vector<int>G[maxn];//存储邻接点

void dfs(int u)
{
	dp[u][1] = 1;
	for (int i = 0; i < G[u].size(); i++)
	{
		int v = G[u][i];
		dfs(v);
		dp[u][0] += dp[v][1];
		dp[u][1] += min(dp[v][0], dp[v][1]);
	}
}
int main()
{
	while (cin >> N)
	{
		memset(dp, 0, sizeof(dp));
		memset(father, -1, sizeof(father));
		int u, m, v;
		for (int i = 0; i < N; i++)
		{
			scanf("%d:(%d)", &u, &m);
			G[u].clear();        //注意清空
			for (int j = 1; j <= m; j++)
			{
				scanf("%d", &v);
				father[v] = u;
				G[u].push_back(v);
			}
		}
		int root = 0;
		while (father[root] != -1) root = father[root];
		dfs(root);
		cout << min(dp[root][0], dp[root][1]) << endl;
	}
	return 0;
}

点赞