二分图匹配模板(dfs+bfs)
dfs版:
- bool dfs(int u)
- {
- for(int i = head[u]; ~i; i = e[i].next) {
- int v = e[i].v;
- if(!vis[v]) {
- vis[v] = true;
- if(my[v] == -1 || dfs(my[v])) {
- my[v] = u;
- mx[u] = v;
- return true;
- }
- }
- }
- return false;
- }
- int hungary()
- {
- int ret = 0;
- memset(mx, -1, sizeof(mx));
- memset(my, -1, sizeof(my));
- for(int i = 1; i <= X; i++) {
- if(mx[i] == -1) {
- memset(vis, 0, sizeof(vis));
- if(dfs(i)) ret++;
- }
- }
- return ret;
- }
bfs版:
- bool bfs(int st)
- {
- queue <int> q;
- q.push(st);
- pre[st] = -1;
- bool flag = false;
- while(!q.empty() && !flag) {
- int u = q.front(); q.pop();
- for(int i = head[u]; ~i && !flag; i = e[i].next) {
- int v = e[i].v;
- if(vis[v] != st) {
- vis[v] = st;
- q.push(my[v]);
- if(~my[v]) pre[my[v]] = u;
- else {
- int a = u, b = v;
- flag = true;
- while(~a) {
- int t = mx[a];
- mx[a] = b;
- my[b] = a;
- a = pre[a];
- b = t;
- }
- }
- }
- }
- }
- return mx[st] != -1;
- }
- int hungary()
- {
- int ret = 0;
- memset(mx, -1, sizeof(mx));
- memset(my, -1, sizeof(my));
- memset(vis, -1, sizeof(vis));
- for(int i = 1; i <= nX; i++) {//number from 1
- if(mx[i] == -1) {
- if(bfs(i)) ret++;
- }
- }
- return ret;
- }
PS:~蒟蒻写博客不易,转载请注明出处,万分感谢!~