Air Raid
题目链接:POJ 1422
题目大意
给你一个有向无环图,问你最少要多少条路径才能覆盖每个点。
思路
最小路径覆盖模板题。
就也是把一个点拆成入点出点,然后入出点构成二分图。
然后你就是要跑这个图的最大匹配,需要的路径就是点数减去最大匹配。
至于为什么你可以理解为这些匹配之间可能可以连起来形成了路径:
a
l
→
b
r
,
b
l
→
c
r
a_l\rightarrow b_r,b_l\rightarrow c_r
al→br,bl→cr
你可以看做中间自动有一个
b
r
→
b
l
b_r\rightarrow b_l
br→bl 然后就连起来了。
那你连起来之后有多少条路径就是多少,那就是点数减去最大匹配。
代码
#include<queue>
#include<cstdio>
#include<iostream>
#include<algorithm>
#define INF 0x3f3f3f3f3f3f3f3f
using namespace std;
const int N = 120 + 10;
int n, m, x, y;
struct node {
int x, to, nxt, op;
}e[(N * N + N << 1) << 1];
int le[N << 1], KK, S, T, tot;
int lee[N << 1], deg[N << 1];
//网络流模板
void add(int x, int y, int z) {
e[++KK] = (node){z, y, le[x], KK + 1}; le[x] = KK;
e[++KK] = (node){0, x, le[y], KK - 1}; le[y] = KK;
}
bool bfs() {
for (int i = 1; i <= tot; i++) lee[i] = le[i], deg[i] = 0;
queue <int> q; q.push(S); deg[S] = 1;
while (!q.empty()) {
int now = q.front(); q.pop();
for (int i = le[now]; i; i = e[i].nxt)
if (e[i].x && !deg[e[i].to]) {
deg[e[i].to] = deg[now] + 1;
if (e[i].to == T) return 1; q.push(e[i].to);
}
}
return 0;
}
int dfs(int now, int sum) {
if (now == T) return sum;
int go = 0;
for (int &i = lee[now]; i; i = e[i].nxt)
if (e[i].x && deg[e[i].to] == deg[now] + 1) {
int this_go = dfs(e[i].to, min(sum - go, e[i].x));
if (this_go) {
e[i].x -= this_go; e[e[i].op].x += this_go;
go += this_go; if (go == sum) return go;
}
}
if (go != sum) deg[now] = -1; return go;
}
int dinic() {
int re = 0;
while (bfs()) re += dfs(S, INF);
return re;
}
int main() {
int TT; scanf("%d", &TT);//多组数据
while (TT--) {
scanf("%d %d", &n, &m);
tot = 2 * n; S = ++tot; T = ++tot;
for (int i = 1; i <= n; i++) add(S, i, 1), add(n + i, T, 1);//建图
for (int i = 1; i <= m; i++) {
scanf("%d %d", &x, &y); add(x, n + y, 1);
}
printf("%d\n", n - dinic());//最小路径覆盖等价于点数减去最大流
for (int i = 1; i <= tot; i++) le[i] = 0; KK = 0;//清空
}
return 0;
}