POJ-1422 Air Raid bipartite graph maximum matching
There are n points and m unidirectional line segments. Now I want to start from a few vertices to traverse all vertices.
Solution: The maximum matching of a bipartite graph. If one match is required, the two points are connected. You only need to select one point for the two points. Therefore, how many matches are there, the number of vertices that can be subtracted.
#include
#include
using namespace std;const int N = 130;int g[N][N], vis[N], link[N];int n, m;void init() { memset(g, 0, sizeof(g)); memset(link, 0, sizeof(link)); int x, y; for(int i = 0; i < m; i++) { scanf("%d%d", &x, &y); g[x][y] = 1; }}bool dfs(int u) { for(int i = 1; i <= n; i++) { if(!vis[i] && g[u][i]) { vis[i] = 1; if(!link[i] || dfs(link[i])) { link[i] = u; return true; } } } return false;}void hungary() { int ans = 0; for(int i = 1; i <= n; i++) { memset(vis, 0, sizeof(vis)); if(dfs(i)) ans++; } printf("%d\n", n - ans);}int main() { int test; scanf("%d", &test); while(test--) { scanf("%d%d", &n, &m); init(); hungary(); } return 0;}