POJ_1422 Air Raid(二分图最大匹配匈牙利算法)
这道题其实就是二分图的最大匹配问题。用构造匈牙利树的方法可以有效的提高求解的效率。
#include <iostream> #include <string.h> #define MAX 121 using namespace std; bool map[MAX][MAX]; int xM[MAX],yM[MAX]; bool cheak[MAX]; int n; bool DFS(int u) { int v = 0; for(v = 0;v <= n;v++) { if(!cheak[v] && map[u][v]) { cheak[v] = true; if(yM[v] == -1 || DFS(yM[v])) { yM[v] = u; xM[u] = v; return true; } } } return false; } int search() { int cot = 0; memset(xM,-1,sizeof(xM)); memset(yM,-1,sizeof(yM)); for(int i = 1;i <= n;i++) { if(xM[i] == -1) { memset(cheak,false,sizeof(cheak)); if(DFS(i)) { cot++; } } } return cot; } int main() { int testnum; int streat; cin>>testnum; for(int i = 0;i < testnum;i++) { cin>>n>>streat; memset(map,false,sizeof(map)); for(int j = 0;j < streat;j++) { int sK,eK; cin>>sK>>eK; map[sK][eK] = true; } cout<<n - search()<<endl; } return 0; }