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个点的树形图,每一个点可以保护与他相连的边,求要保护所有边时,最少的顶点数。)
(思路:本来想找个二分匹配的题学习学习,没想到还是个最小顶点覆盖。最小顶点覆盖=最大匹配数/2(无向图)
参考博客:https://blog.csdn.net/qq_41730082/article/details/81162561
https://blog.csdn.net/u010270403/article/details/10048577
)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
#include <stack>
#define ll long long
using namespace std;
const int N=1510;
int head[N],cnt,n,match[N],vis[N];
//match[i]:i的匹配点
//vis[i]:i有没有被匹配
struct node
{
int to,next;
}E[N*N];
//初始化
void Init()
{
for(int i=0;i<n;i++)
head[i]=-1,match[i]=-1;
cnt=0;
return ;
}
void add(int u,int v)
{
E[cnt].to=v;
E[cnt].next=head[u];
head[u]=cnt++;
return ;
}
//dfs找增广路
int dfs(int x)
{
for(int i=head[x];i!=-1;i=E[i].next)
{
int y=E[i].to;
//如果匹配了直接跳过
if(vis[y]) continue;
vis[y]=1;//标记已匹配
//如果y点不在增广路径上,或者从y的邻接点可以找到一条增广路径
if(match[y]==-1||dfs(match[y]))
{
match[y]=x;
return 1;
}
}
return 0;
}
int hungary()
{
int ans=0;
for(int i=0;i<n;i++)
{
//每次都要初始化
for(int j=0;j<n;j++)
vis[j]=0;
//找i点开始的增广路径
if(dfs(i))
ans++;
}
return ans;
}
int main(void)
{
while(~scanf("%d",&n))
{
Init();
for(int i=0;i<n;i++)
{
int u,m;
scanf("%d:(%d)",&u,&m);
while(m--)
{
int v;
scanf("%d",&v);
add(u,v);
add(v,u);
}
}
int ans=hungary();
printf("%d\n",ans/2);
}
return 0;
}