Strategic Game HDU - 1054 (匈牙利,最小顶点覆盖)

 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:

Strategic Game HDU - 1054 (匈牙利,最小顶点覆盖)_第1张图片

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:

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)

Output

1
2

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

题意:鲍勃喜欢玩电脑游戏,特别是战略游戏,但有时他找不到足够快的解决方案,他很伤心。现在他有以下问题。他必须保卫一座中世纪的城市,这条道路就是一棵树。他必须把最小数量的士兵放在节点上,这样他们才能观察到所有的边缘。你能帮助他吗?您的程序应该找到Bob必须为给定树放置的最小数量的士兵

解题思路:最小顶点覆盖问题,由König定理定理可知,二分图的最小顶点覆盖数等于二分图的最大匹配数。
题目中的这棵树之所以可以当成二分图,是因为如果从一个点出发,那么可以将整棵树分成奇数点层和偶数点层。由于树是一种特殊的图。n个点由(n-1)条边连接起来。这样假定一个点为树的根,假设各点间的边权值为1。那么从树根出发遍历整棵树,根据各点到根的路径的奇偶性即可将所有点分成两个集合。奇数点与偶数点交替出现。假设奇数点与偶数点连边,偶数点则继续和下一层的奇数点连边。这就与二分图中同类集合点间无边,不同类集合点间有边相连吻合起来了。所以满足二分图的性质。也可以用二分图最大匹配进行求解。由于对该二分图进行了补全(无向图),边增加为原来边的二倍。所以最终结果要除以2。
二分图最小顶点覆盖=双向二分图最大匹配/2
http://blog.csdn.net/draven__/article/details/76974092

#include
#include
#include
#include
using namespace std;
const int N=1500+5;
vector<int > G[N];//数据量较大
int visit[N];
int match[N];
int n;
int Find(int u)
{
    for(int i=0;iint v=G[u][i];
        if(!visit[v])
        {
            visit[v]=1;
            if(match[v]==0 ||Find(match[v]))
            {
                match[v]=u;
                return 1;
            }
        }
    }
  return 0;
}
int main()
{
    int m,k;
    while(~scanf("%d",&n))
    {
        for(int i=0;iscanf("%d:(%d)",&m,&k);
            for(int j=0;jint a;
                scanf("%d",&a);
                G[a].push_back(m);//双向图
                G[m].push_back(a);
            }
        }
        memset(match,0,sizeof(match));
        int ans=0;
        for(int i=0;imemset(visit,0,sizeof(visit));
            if(Find(i))
                ans++;
        }
        printf("%d\n",ans/2);
        for(int i=0;ireturn 0;
}

你可能感兴趣的:(匹配)