POJ 3041 Asteroids

匈牙利算法模板

C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#define M 500

using namespace std;

bool grid[M][M];
bool vis[M];//本轮是否已经尝试通过y来增广并且失败
int n, k;
int cnt;
int link[M];

bool dfs(int x){
for(int i = 1; i <= n; i++){
if(grid[x][i] && !vis[i]){
vis[i] = true;
if(link[i] == -1 || dfs(link[i]) == true){
link[i] = x;
return true;
}
}
}
return false;
}

void search(){
for(int i = 1; i <= n; i++){
memset(vis, false, sizeof(vis));
if(dfs(i))
cnt++;
}
}

int main(){
int x, y;
while(~scanf("%d%d", &n, &k)){
memset(link, -1, sizeof(link));
memset(grid, false, sizeof(grid));
for(int i = 0; i < k; i++){
scanf("%d%d", &x, &y);
grid[x][y] = true;
}
cnt = 0;
search();
printf("%d\n", cnt);
}
return 0;
}