匈牙利算法模板&nyoj239
1 #include <bits/stdc++.h> 2 using namespace std; 3 vector<int> v[510]; 4 int match[510]; 5 int check[510]; 6 int n, k; 7 int dfs(int x) 8 { 9 for(int i = 0; i < v[x].size(); i++) 10 { 11 int t = v[x][i]; 12 if (check[t] == 0) 13 { 14 check[t] = 1; 15 if(match[t] == 0 || dfs(match[t])) 16 { 17 match[t] = x; 18 return 1; 19 } 20 } 21 } 22 return 0; 23 } 24 void init() 25 { 26 for(int i = 0; i <= n; i++) 27 v[i].clear(); 28 memset(match, 0, sizeof(match)); 29 } 30 int hungarian() 31 { 32 int sum = 0; 33 for(int i = 1; i <= n; i++) 34 { 35 memset(check, 0, sizeof(check)); 36 if(dfs(i)) 37 sum++; 38 } 39 return sum; 40 } 41 int main() 42 { 43 int t; 44 scanf("%d", &t); 45 while(t--) 46 { 47 init(); 48 scanf("%d%d", &n, &k); 49 int s, e; 50 for(int i = 0; i < k; i++) 51 { 52 scanf("%d%d", &s, &e); 53 v[s].push_back(e); 54 } 55 printf("%d\n", hungarian()); 56 } 57 }