题目链接:http://poj.org/problem?id=3659
Description
Farmer John has decided to give each of his cows a cell phone in hopes to encourage their social interaction. This, however, requires him to set up cell phone towers on hisN (1 ≤ N ≤ 10,000) pastures (conveniently numbered 1..N) so they can all communicate.
Exactly N-1 pairs of pastures are adjacent, and for any two pastures A and B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B) there is a sequence of adjacent pastures such that A is the first pasture in the sequence and B is the last. Farmer John can only place cell phone towers in the pastures, and each tower has enough range to provide service to the pasture it is on and all pastures adjacent to the pasture with the cell tower.
Help him determine the minimum number of towers he must install to provide cell phone service to each pasture.
Input
* Line 1: A single integer: N
* Lines 2..N: Each line specifies a pair of adjacent pastures with two space-separated integers:A and B
Output
* Line 1: A single integer indicating the minimum number of towers to install
Sample Input
5 1 3 5 2 4 3 3 5
Sample Output
2
Source
题意是给你一棵树,每个点可以覆盖相邻的点,求用最少的点覆盖所有的点。
题意是求树的最小支配集,不过自己刚学到这里,于是参考了大牛的讲解...http://blog.csdn.net/crescent__moon/article/details/12792587
树形DP求解思路:
根据题意每个节点有以下三种状态
1.u自己建塔,u的所有孩子都被覆盖,用dp[u][0]表示
2.u不建塔,u和u的所有孩子都被覆盖,用dp[u][1]表示
3.u不建塔,u不覆盖,u的所有孩子被覆盖,用dp[u][2]表示
有人用了更加直白的解释,就是u要么被自己覆盖,要么被自己的孩子覆盖,要么被自己的父亲覆盖
1.被自己覆盖 dp[u][0]
2.被自己的孩子覆盖dp[u][1]
3.被自己的父亲覆盖dp[u][2]
状态转移方程
dp[u][0]+=min(dp[v][0],dp[v][1],dp[v][2]);
dp[u][2]+=min(dp[v][0],dp[v][1]);
对于dp[u][1],要保证必须有一个孩子建塔才能把自己覆盖,所以加上其中最小的
if(dp[to][0]<=dp[to][1])
flag=false;
dp[u][1]+=dp[to][0];
else
dp[u][1]+=dp[to][1]
否则dp[u][1]+=min(dp[to][0]-dp[to][1])
然后以1为起点开始搜,最终应该是min(dp[1][0],dp[1][1]),因为其根节点必须被覆盖。。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=10005;
const int inf=1<<31-1;
struct node
{
int to,next;
}e[maxn*2];
int dp[maxn][3];
int vis[maxn],head[maxn*2];
int n,cnt;
void add(int x,int y)
{
e[cnt].to=y;
e[cnt].next=head[x];
head[x]=cnt++;
}
void dfs(int u)
{
bool flag=true;
dp[u][0]=1;
dp[u][1]=dp[u][2]=0;
vis[u]=1;
int minn=inf;
for(int k=head[u];k!=-1;k=e[k].next)
{
int to=e[k].to;
if(!vis[to])
{
dfs(to);
dp[u][0]+=min(dp[to][0],min(dp[to][1],dp[to][2]));
dp[u][2]+=min(dp[to][0],dp[to][1]);
if(dp[to][0]<=dp[to][1])
{
flag=false;
dp[u][1]+=dp[to][0];
}
else
{
dp[u][1]+=dp[to][1];
minn=min(minn,dp[to][0]-dp[to][1]);
}
}
}
if(flag)
dp[u][1]+=minn;
}
int main()
{
//freopen("in.txt","r",stdin);
while(cin>>n)
{
cnt=0;
memset(vis,0,sizeof(vis));
memset(head,-1,sizeof(head));
for(int i=1;i<n;i++)
{
int a,b;
cin>>a>>b;
add(a,b);
add(b,a);
}
dfs(1);
cout<<min(dp[1][0],dp[1][1])<<endl;
}
return 0;
}