http://acm.hdu.edu.cn/showproblem.php?pid=1151
题意:给你n个城镇和m条边,边是单向的且图中没有环。选择一些小兵空降在城镇上,小兵可以沿着单向边走到路的尽头,问最少需要多少个小兵可以遍历所有的顶点。
思路:最小边覆盖,用尽量少的不相交简单路径覆盖有向无环图(DAG)G的所有顶点。依旧是定理[金馆长哭],怎么这几道题都是定理啊,想吐槽。
在任意图中:
(a)、对于不存在孤立点的图,最大匹配+最小边覆盖=顶点数;
(b)、最大独立集+最小顶点覆盖=顶点数;
二分图中:
(c)、最大匹配=最小顶点覆盖。
就是这几个定理,下一篇我准备好好把定理概念以及匈牙利算法思路简单整理一下。
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <stack>
#include <ctype.h>
using namespace std;
typedef long long LL;
const int N = 505;
const int INF = 0x3f3f3f3f;
int head[N], match[N];
bool vis[N];
int n, m, cnt;
struct Edge
{
int to,next;
}edge[N*N];
void add(int u, int v)
{
edge[cnt] = (struct Edge){v, head[u]};
head[u] = cnt++;
}
void init()
{
cnt = 0;
memset(head, -1, sizeof(head));
}
bool Augment(int u)
{
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(!vis[v])
{
vis[v] = true;
if(match[v]==-1 || Augment(match[v]))
{
match[v] = u;
return true;
}
}
}
return false;
}
int Hungary(int n)
{
int ans = 0;
memset(match, -1, sizeof(match));
for(int i = 1; i <= n; i++)
{
memset(vis, false, sizeof(vis));
if(Augment(i)) ans++;
}
return ans;
}
int main()
{
// freopen("in.txt", "r", stdin);
int t, n, u, v, k;
scanf("%d", &t);
while(t--)
{
init();
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++)
{
scanf("%d%d", &u, &v);
add(u, v);
}
printf("%d\n", n-Hungary(n));
}
return 0;
}