您的位置:首页 > 其它

文章标题

2017-10-12 20:43 162 查看
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


数据量大,用Hopcroft-Carp算法,建图

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1505;
int Mx[MAXN], My[MAXN], dx[MAXN], dy[MAXN];
int dis;
int g[MAXN][MAXN];
bool vis[MAXN];
int M;
int Nx, Ny;
bool SearchP()
{
queue<int> Q;
dis = INF;
memset(dx, -1, sizeof(dx));
memset(dy, -1, sizeof(dy));
for(int i=0;i<Nx;i++)
{
if(Mx[i]==-1)
{
Q.push(i);
dx[i] = 0;
}
}
while(!Q.empty())
{
int u = Q.front();
Q.pop();
if(dx[u] > dis)
break;
for(int v=0;v<Ny;v++)
{
if(g[u][v]&&dy[v]==-1)
{
dy[v] = dx[u] + 1;
if(My[v]==-1)
dis = dy[v];
else
{
dx[My[v]] = dy[v] + 1;
Q.push(My[v]);
}
}
}
}
return dis!=INF;
}
bool DFS(int u)
{
for(int v=0;v<Ny;v++)
{
if(!vis[v]&&g[u][v]&&dy[v]==dx[u]+1)
{
vis[v] = 1;
if(My[v]!=-1&&dy[v]==dis)
continue;
if(My[v]==-1||DFS(My[v]))
{
My[v] = u;
Mx[u] = v;
return true;
}
}
}
return false;
}
int MaxMatch()
{
memset(Mx, -1, sizeof(Mx));
memset(My, -1, sizeof(My));
while(SearchP())
{
memset(vis, false, sizeof(vis));
for(int i=0;i<Nx;i++)
{
if(Mx[i]==-1&&DFS(i))
M++;
}
}
return M;
}
int main()
{
int n;
while(~scanf("%d", &n))
{
memset(g, 0, sizeof(g));
Nx = Ny = n;
M = 0;
for(int i=0;i<n;i++)
{
int a, b, c;
scanf("%d:(%d)", &a, &b);
while(b--)
{
scanf("%d", &c);
g[a][c] = 1;
g[c][a] = 1;
}
}
printf("%d\n", MaxMatch()/2);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: