跳到正文

个人记录

匈牙利算法优化

pengyulun约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年1月26日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
const int N=505,M=5e4+8;
struct G{int x,t;} a[M];
int n,m,e,w[N],h[N],cnt=0,k[N];
bool dfs(int x){
	w[x]=1;
	for (int i=h[x],j=0;i;j=i,i=a[i].t){
			if (k[a[i].x]==0||(w[k[a[i].x]]==0&&dfs(k[a[i].x]))){
			k[a[i].x]=x;w[x]=0;return 1;
		}else if (w[k[a[i].x]]==2){
			if (j==0) h[x]=a[i].t;
			else a[j].t=a[i].t;
		}
	}
	w[x]=2;
	return 0;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
	cin >>n>>m>>e;
	for (int i=1,x,y;i<=e;++i){
		cin >>x>>y;
		a[++cnt]={y,h[x]},h[x]=cnt;
	}
	int ans=0;
	for (int i=1;i<=n;++i){
		if (dfs(i)) ++ans;
	}
	cout <<ans;
	return 0;
}
原文