hdu_1054 Strategic Game(动态规划与二分图两种解法)

来源:互联网 发布:抽奖算法提高概率 编辑:程序博客网 时间:2024/05/21 21:36
Problem 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.

The input file 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_identifier
or
node_identifier:(0)

The node identifiers are integer numbers between 0 and n-1, for n nodes (0 < n <= 1500). Every edge appears only once in the input data.

For example for the tree: 

 

the solution is one soldier ( at the node 1).

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 table:
 

Sample Input
40:(1) 11:(2) 2 32:(0)3:(0)53:(3) 1 4 21:(1) 02:(0)0:(0)4:(0)
 

Sample Output
12
这题可以dp与二分图都可以解 。
用dp解的话有这样的状态方程
dp[i][0] = sum(d[j][1]);
dp[i][1] = sum(min(d[j][0],d[j][1]) + 1;
i表示父亲节点,j表示子节点。
代码如下
#include <cstdio>#include <cstring>#define min(a, b) a>b ? b : a#define N 1501int g[N][N];int d[N][2];int main(){int x, y, m, n;while(~scanf("%d", &n)){memset(d, 0, sizeof(d));memset(g, 0, sizeof(g));for(int i=0; i<n; ++i){scanf("%d", &x);getchar();getchar();scanf("%d", &m);getchar();getchar();while(m--){scanf("%d", &y);g[x][y] = 1;g[y][x] = 1;}}for(int i=n-1; i>=0; --i){d[i][0] = 0;d[i][1] = 1;for(int j=i+1; j<n; ++j)if(g[i][j]){d[i][0] += d[j][1];d[i][1] += min(d[j][1],d[j][0]);}}printf("%d\n", min(d[0][1],d[0][0]));}}

二分图解法的代码如下
#include <cstdio>#include <cstring>#define N 1501bool g[N][N];int n;bool v[N];int con[N];bool dfs(int u){for(int i=0; i<n; ++i){if(g[u][i] && !v[i]){v[i] = 1;if(!con[i] || dfs(con[i])){v[i] = 0;con[i] = u;return 1;}v[i] = 0;}}return 0;}int main(){int x, y, m;while(~scanf("%d", &n)){std::memset(g, 0, sizeof(g));std::memset(v, 0, sizeof(v));std::memset(con, 0, sizeof(con));for(int i=0; i<n; ++i){scanf("%d", &x);getchar();getchar();scanf("%d", &m);getchar();getchar();while(m--){scanf("%d", &y);g[x][y] = 1;g[y][x] = 1;}}m = 0;for(int i=0; i<n; ++i)if(dfs(i))++m;printf("%d\n",m/2);}}


0 0