最大匹配(二分图、一般图)
二分图最大匹配
匈牙利算法
const int N=510;
int n,m,e,Match[N],u,v,ans;
bool Vis[N],E[N][N];
inline int dfs(int x){
for(int i=1; i<=m; ++i)
if(!Vis[i] && E[x][i]){
Vis[i]=true;
if(!Match[i] || dfs(Match[i])){
Match[i]=x;
return 1;
}
}
return 0;
}
int main(){
scanf("%d%d%d",&n,&m,&e);
for(int i=1; i<=e; ++i)
scanf("%d%d",&u,&v),
E[u][v]=true;
for(int i=1; i<=n; ++i)
ans+=dfs(i),
memset(Vis,false,sizeof(Vis));
printf("%d",ans);
return 0;
}
二分图最大权完美匹配
struct KuhnMunkres{
long long G[N][N], lx[N], ly[N], slack[N];
int n, px[N], py[N], pre[N];
bool vx[N], vy[N];
void aug(int v){
if(px[pre[v]]) aug(px[pre[v]]);
px[py[v]=pre[v]] = v;
}
void bfs(int s){
memset(vx, 0, sizeof(vx)); memset(vy, 0, sizeof(vy));
memset(pre, 0, sizeof(pre));
memset(slack, 0x3f, sizeof(slack));
queue<int> q; q.push(s); vx[s] = 1;
while(true){
while(!q.empty()){
int u = q.front(); q.pop(); vx[u] = 1;
for(int v = 1; v <= n; ++ v) if(!vy[v]){
if(lx[u] + ly[v] - G[u][v] < slack[v]){
slack[v] = lx[u] + ly[v] - G[u][v];
pre[v] = u;
}
if(!slack[v]){
vy[v] = 1;
if(!py[v]){ aug(v); return; }
else q.push(py[v]), vx[py[v]] = 1;
}
}
}
long long d = 0x3f3f3f3f3f3f3f3f;
for(int i = 1; i <= n; ++ i) if(!vy[i]) d = min(d, slack[i]);
for(int i = 1; i <= n; ++ i){
if(vx[i]) lx[i] -= d;
if(vy[i]) ly[i] += d; else slack[i] -= d;
}
for(int v = 1; v <= n; ++ v) if(!vy[v])
if(!slack[v]){
vy[v] = 1;
if(!py[v]){ aug(v); return; }
else q.push(py[v]), vx[py[v]] = 1;
}
}
}
void init(){ memset(lx, 0xcf, sizeof(lx)); memset(G, 0xcf, sizeof(G)); }
void add(int u, int v, long long w){ G[u][v] = w, lx[u] = max(lx[u], w); }
void solve(){ for(int i = 1; i <= n; ++ i) bfs(i); }
void print(){
long long ans = 0;
for(int i = 1; i <= n; ++ i) ans += G[py[i]][i];
printf("%lld\n", ans);
for(int i = 1; i <= n; ++ i) printf("%d ", py[i]);
}
} KM;