PS: 1. 有向图 2.不存在环 即DAG。网上有对图进行拆点然后求解最大匹配,有的直接对原图求最大匹配。
如果对图进行拆点,重构新图:
首先建图:先拆点,将每个点分为两个点,左边是1到n个点,右边是1-n个点
然后每一条有向边对应左边的点指向右边的点
这样建好图之后求最大匹配数
因为最小路径覆盖=点数-最大匹配数
两份代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <vector>
using namespace std;
const int MAX = 130;
vector<int> G[MAX];
int n, m;
int from[MAX], tot;
bool use[MAX];
bool match(int x) {
for(int i = 0; i < (int)G[x].size(); i++) {
int &u = G[x][i];
if(!use[u]) {
use[u] = true;
if(from[u]==-1 || match(from[u])) {
from[u] = x;
return true;
}
}
}
return false;
}
int hungary() {
tot = 0;
memset(from, 255, sizeof(from));
for(int i = 1; i <= n; i++) {
memset(use, 0, sizeof(use));
if(match(i)) {
tot++;
}
}
return tot;
}
int main()
{
int T;
scanf("%d", &T);
while(T--) {
int x, y;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++) G[i].clear();
for(int i = 0; i < m; i++) {
scanf("%d%d", &x, &y);
G[x].push_back(y);
}
int res = hungary();
printf("%d\n", n-res);
}
return 0;
}
#include<iostream>
#include<vector>
#include <cstring>
#include <cstdio>
#define N 205
using namespace std;
vector<int> G[N];
int vis[N];
int match[N];
int n;
int dfs(int u)
{
for(int i = 0; i<(int)G[u].size(); i++){
int v = G[u][i];
if(!vis[v]) {
vis[v] = 1;
if(match[v]==-1 || dfs(match[v])){
match[v] = u;
return 1;
}
}
}
return 0;
}
int hungary()
{
memset(match, -1, sizeof(match));
int ret = 0;
for(int i=1; i<=n; i++) {
memset(vis, 0, sizeof(vis));
ret += dfs(i);
}
return ret;
}
int main(void)
{
int t, m, a, b;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
for(int i=0; i<=n; i++) G[i].clear();
scanf("%d", &m);
while(m--) {
scanf("%d%d", &a, &b);
G[a].push_back(b);
}
printf("%d\n", n-hungary());
}
return 0;
}