Cell Phone Network
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7241 | Accepted: 2581 |
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 his N (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
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define MAXN 10010
#define INF 0x3f3f3f3f
vector <int> G[MAXN];
int dp[MAXN][MAXN]; //dp[i][0]表示取i结点时的最小结点数
//dp[i][1]表示不取i结点时,i被其儿子覆盖时的最小结点数
//dp[i][2]表示不选点i,i被其父亲覆盖时的最小结点数
//树形DP状态转移从叶子结点开始向根不断转移,所以用深搜。
//搜到叶子结点就结束。
//转移的时候可以将结点以下给圈起来。
//取与不取,树上背包
int vis[MAXN];
void dfs(int u)
{
vis[u]=1;
int i;
int flag=1,tmp=INF;
for(i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(!vis[v]) //额,图的最小支配集吧
{
dfs(v);
dp[u][0]+=min(dp[v][0],min(dp[v][1],dp[v][2]));
dp[u][2]+=min(dp[v][0],dp[v][1]); //不取的话,肯定没有父亲这个选项啊
//父亲只有一个,所以不必做过多的讨论
//儿子比较多,可以取所有儿子,但必须选一个儿子
//但选了一个儿子就要做标记
if(dp[v][0]<=dp[v][1])
{
dp[u][1]+=dp[v][0];
flag=0;
}
else
{
dp[u][1]+=dp[v][1];
tmp=min(tmp,dp[v][0]-dp[v][1]);
}
}
}
if(flag) //还没有选儿子,加上这个差值,补回一个儿子
dp[u][1]+=tmp;
return ;
}
int main()
{
int n;
int i=0;
int u,v;
scanf("%d",&n);
for(i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
for(i=0;i<=n;i++) //dp[i][0]的i从0开始,因为存在下标为0的结点
{ //再次强调结点的下标一定是0~n-1
dp[i][0]=1;
dp[i][1]=0;
dp[i][2]=0;
}
if(n==1)
printf("1\n");
else
{
dfs(1);
printf("%d\n",min(dp[1][0],dp[1][1]));
}
return 0;
}