AcWing 379. 捉迷藏(最小路径覆盖)

题目

Vani和cl2在一片树林里捉迷藏。

这片树林里有N座房子,M条有向道路,组成了一张有向无环图。

树林里的树非常茂密,足以遮挡视线,但是沿着道路望去,却是视野开阔。

如果从房子A沿着路走下去能够到达B,那么在A和B里的人是能够相互望见的。

现在cl2要在这N座房子里选择K座作为藏身点,同时Vani也专挑cl2作为藏身点的房子进去寻找,为了避免被Vani看见,cl2要求这K个藏身点的任意两个之间都没有路径相连。

为了让Vani更难找到自己,cl2想知道最多能选出多少个藏身点。

输入格式

输入数据的第一行是两个整数N和M。

接下来M行,每行两个整数 x,y,表示一条从 x 到 y 的有向道路。

输出格式

输出一个整数,表示最多能选取的藏身点个数。

数据范围

N≤200,M≤30000

思路

DAG的最大独立集 = 最小路径覆盖,最小路径覆盖 = 点数 – 最大匹配数,把原图拆点做最小路径覆盖即可

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
const int N=207,M=30007;
int n,m;
bool d[N][N],st[N];
int match[N];

bool find(int x)
{
	for(int i=1;i<=n;i++)
	{
		if(d[x][i]&&!st[i])
		{
			
			st[i]=true;
			int t=match[i];
			if(t==0||find(t))
			{
				match[i]=x;
				return true;
			}
		}
	}
	return false;
}

int main()
{
	//freopen("test.in","r",stdin);//设置 cin scanf 这些输入流都从 test.in中读取
    //freopen("test.out","w",stdout);//设置 cout printf 这些输出流都输出到 test.out里面去
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	cin>>n>>m;
	while(m--)
	{
		int a,b;
		cin>>a>>b;
		d[a][b]= true;
	}
	for(int k=1;k<=n;k++)
	{
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=n;j++)
			{
				d[i][j]|=d[i][k]&d[k][j];
			}
		}
	}
	int res=0;
	for(int i=1;i<=n;i++)
	{
		memset(st,0,sizeof st);
		if(find(i)) res++;
	}
	cout<<n-res<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44828887/article/details/107436615
今日推荐