题目来源:
http://poj.org/problem?id=1463
题目描述:
Description
Bob enjoys playing computer games, especially strategic games, but sometimes he cannot find the solution fast enough and then he is very sad. Now he has the following problem. He must defend a medieval city, the roads of which form a tree. He has to put the minimum number of soldiers on the nodes so that they can observe all the edges. Can you help him?
Your program should find the minimum number of soldiers that Bob has to put for a given tree.
For example for the tree:
the solution is one soldier ( at the node 1).
Input
The input contains several data sets in text format. Each data set represents a tree with the following description:
- the number of nodes
- the description of each node in the following format
node_identifier:(number_of_roads) node_identifier1 node_identifier2 ... node_identifiernumber_of_roads
or
node_identifier:(0)
The node identifiers are integer numbers between 0 and n-1, for n nodes (0 < n <= 1500);the number_of_roads in each line of input will no more than 10. Every edge appears only once in the input data.
Output
The output should be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the minimum number of soldiers). An example is given in the following:
Sample Input
4 0:(1) 1 1:(2) 2 3 2:(0) 3:(0) 5 3:(3) 1 4 2 1:(1) 0 2:(0) 0:(0) 4:(0)
Sample Output
1 2
解题思路:
本题和舞会那题很像,树形dp,也是用dp【i】【0/1】表示状态,1表示取i的最小值,0表示不取i的最小值,然后写出转移方程就行
-
dp[root][1] += min(dp[tree[root][i]][1],dp[tree[root][i]][0]) ;
-
dp[root][0] += dp[tree[root][i]][1]
记得要找到根节点为起点
代码:
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn=1510;
int n,dp[maxn][2],head[maxn],fa[maxn],cnt=0;
struct newt
{
int to,next;
}e[maxn*10];
void addedge(int u,int v)
{
e[cnt].to=v;
e[cnt].next=head[u];
head[u]=cnt++;
}
void dfs(int u)
{
dp[u][1]=1;
dp[u][0]=0;
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].to;
dfs(v);
dp[u][0]+=dp[v][1];
dp[u][1]+=min(dp[v][0],dp[v][1]);
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(head,-1,sizeof(head));
memset(fa,-1,sizeof(fa));
memset(dp,0,sizeof(dp));
cnt=0;
for(int i=1,a,b;i<=n;i++)
{
scanf("%d:(%d)",&a,&b);
for(int j=1,x;j<=b;j++)
{
scanf("%d",&x);
fa[x]=a;
addedge(a,x);
}
}
int S=1;
while(fa[S]!=-1)S=fa[S];
dfs(S);
printf("%d\n",min(dp[S][0],dp[S][1]));
}
return 0;
}