`Time Limit: 2000MS Memory Limit: 10000K
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
参考网上的代码,有说是二部图算法的,也有说是用vector创建二维动态数组的(据说直接用数组会不够啊),大部分思路都是用邻接表,然后遍历,最后输出遍历结果的一半就是最终结果。这里给出树形动归的代码,简单的动态规划推理过程,注释在代码里给的很详细。
/*
从上至下,从左至右遍历,树形动态规划
dp[i][1]来表示第i个结点放置哨兵,dp[i][0]来表示第i个结点不放置哨兵
父节点放了,子节点可放可不放;
父节点没放,子节点必须放。
dp[v][1] += min(dp[u][1],dp[u][0])
dp[v][0] += dp[u][1]
*/
#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
#define maxn 2000
bool father[maxn]; //判断有无父节点,无的话,可以当做根节点
int brother[maxn];
int son[maxn];//孩子节点,只保留一个,因为其他的可以通过兄弟节点找到
int dp[maxn][2];
int leaf, cnt, root, des, res, result;//从des到res
int my_min(int a, int b)
{
return a < b ? a : b;
}
void travel(int root)
{
dp[root][0] = 0;
dp[root][1] = 1;
int s = son[root]; //求子节点
while (s != -1) //也就是还有子节点,横向继续遍历
{
travel(s); //深度优先遍历
dp[root][1] += my_min(dp[s][0], dp[s][1]); //父亲放了,儿子可以放,也可以不放
dp[root][0] += dp[s][1]; //父亲不放,儿子就必须放
s = brother[s]; //切换到下一个兄弟结点,横向遍历
}
}
int main()
{
int i, j;
while (cin >> leaf)
{
memset(son, -1, sizeof(son));
memset(father, false, sizeof(father));
for (i = 0; i<leaf; i++)
{
scanf("%d:(%d)", &des, &cnt);
for (j = 0; j<cnt; j++)
{
cin >> res;
brother[res] = son[des]; //同一个父节点的上一个兄弟
son[des] = res; //des的儿子是res,更新儿子节点,可以记录多个
father[res] = true; //res是有父亲的,为下面找根结点做准备
}
}
for (i = 0; i<leaf; i++)
{
if (!father[i]) //如果没有父亲就可以做为根结点
{
root = i;
break;
}
}
travel(root);
result = my_min(dp[root][1], dp[root][0]);
cout << result << endl;
}
return 0;
}