Strategic Game (二分匹配)

Strategic Game

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: 

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

这道题也是一道最小点覆盖的问题,求至少要几个点才能满足题意。

柯尼希定理:二分图最小点覆盖的点数=最大匹配数。

最小路径覆盖的边数=顶点数n-最大匹配数

最大独立集=最小路径覆盖=顶点数n-最大匹配数

有公式可知,求最小点覆盖就是求最大匹配所以我们只要建图就行了,接下来就不难了。因为这里是无向图,所以最大匹配要除以2

#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
#define mmm(a,b) memset(a,b,sizeof(a))
const int N=2000;
int n;
int book[N];
int match[N];
vector<int> e[N];
int dfs(int u)
{
   for(int i=0;i<e[u].size();i++)
   {
       int v=e[u][i];//代表那个点
       if(book[v]) continue;
       book[v]=1;
       if(match[v]==-1||dfs(match[v]))
       {
           match[v]=u;
           return 1;
       }
   }
   return 0;
}
int main()
{
    int a,b,c;
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;i++) e[i].clear();
        for(int i=0;i<n;i++)
        {
            scanf("%d:(%d)",&a,&b);
            for(int j=0;j<b;j++)
            {
                scanf("%d",&c);
                e[a].push_back(c);
                e[c].push_back(a);
            }
        }
        int ans=0;
        mmm(match,-1);
        for(int i=0;i<n;i++)
        {
            mmm(book,0);
            if(dfs(i)) ans++;
        }
//        for(int i=0;i<n;i++)
//        {
//            printf("%d\n",match[i]);
//        }
        printf("%d\n",ans/2);
    }
}
/*
3
0:(1)1
1:(1)2
2:(0)
*/

猜你喜欢

转载自blog.csdn.net/qq_40510246/article/details/81385175
今日推荐