题目
监狱有N条道路连接N + 1个交点,编号0至N,整个监狱被这些道路连在一起(任何2点之间都有道路),人们通过道路在交点之间走来走去。其中的一些交点只有一条路连接,这些点是监狱的出口。在各个交点中有M个点住着犯人(M <= N + 1),剩下的点可以安排警卫,有警卫把守的地方犯人无法通过。给出整个监狱的道路情况,以及犯人所在的位置,问至少需要安排多少个警卫,才能保证没有1个犯人能够逃到出口,如果总有犯人能够逃出去,输出-1。
分析
我们来考虑一下,放完警卫后,这个树形图上每个点的状态会是怎么样的。
状态一. 这个点的子树上的逃犯逃不到这个点,这个点也无法通向的它子树的叶子节点
状态二. 这个点的子树上的逃犯逃不到这个点,这个点有通向其叶子节点的路径
状态三. 这个点的子树上的逃犯能到达这个节点,这个节点无法通向其子树的叶子节点。
除此之外,如果这个图拥有其他状态的点,那么绝对不合法。
这里在我们更新子节点的时候不用考虑这个节点父亲节点的状况,因为父亲节点的状态就是由子节点唯一确定的。
状态很少,所以我们可以很轻易的枚举所有状态。 由此可以写出dp数组的定义
代码
#include <bits/stdc++.h>
const int N = 100005;
int read()
{
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}
while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
struct Edge
{
int to,next;
}e[N * 2];
int next[N];
int cnt;
void add(int x,int y)
{
e[++cnt].to = y, e[cnt].next = next[x], next[x] = cnt;
}
int n,m;
int ans;
int f[N];
int peo[N];
void dfs(int x,int fa)
{
int s[3] = {0,0,0};
for (int i = next[x]; i; i = e[i].next)
{
int v = e[i].to;
if (v == fa)
continue;
dfs(v, x);
s[f[v]]++;
}
if (peo[x])
{
f[x] = 2;
ans += s[0];
}
else
if (s[2] && s[0])
{
ans++;
f[x] = 1;
}
else
if (s[0])
{
f[x] = 0;
}
else
if (s[2])
{
f[x] = 2;
}
else
if (s[1])
f[x] = 1;
}
int d[N];
int main()
{
n = read(), m = read();
for (int i = 1; i <= n; i++)
{
int x = read(), y = read();
d[x]++, d[y]++;
add(x,y);
add(y,x);
}
for (int i = 1; i <= m; i++)
{
int x = read();
peo[x] = 1;
}
for (int i = 1; i < n; i++)
{
if (d[i] == 1)
{
dfs(i, -1);
if (f[i] == 2)
ans++;
printf("%d\n",ans);
break;
}
}
}