P3386 【模板】二分图最大匹配
网络流
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #include<cmath> #include<ctime> #include<set> #include<map> #include<stack> #include<cstring> #define inf 2147483647 #define ls rt<<1 #define rs rt<<1|1 #define lson ls,nl,mid,l,r #define rson rs,mid+1,nr,l,r #define N 1000010 #define For(i,a,b) for(long long i=a;i<=b;i++) #define p(a) putchar(a) #define g() getchar() using namespace std; long long n,m,x,y,v,k; void in(long long &x){ long long y=1;char c=getchar();x=0; while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();} while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();} x*=y; } void o(long long x){ if(x<0){p('-');x=-x;} if(x>9)o(x/10); p(x%10+'0'); } struct Dinic{ long long maxflow,tot; long long head[N],deep[N],cur[N]; queue<long long>q; struct node{ long long n; long long v; long long next; }e[N]; void init(){ memset(head,-1,sizeof(head)); } void push(long long x,long long y,long long v){ e[tot].n=y; e[tot].v=v; e[tot].next=head[x]; head[x]=tot++; } bool bfs(long long s,long long t){ memset(deep,-1,sizeof(deep)); For(i,0,n+m+2) cur[i]=head[i]; deep[s]=0; q.push(s); while(!q.empty()){ long long now=q.front(); q.pop(); for(long long i=head[now];i!=-1;i=e[i].next) if(deep[e[i].n]==-1 && e[i].v>0){ deep[e[i].n]=deep[now]+1; q.push(e[i].n); } } return deep[t]!=-1; } long long dfs(long long now,long long t,long long lim){ if(now==t||lim==0) return lim; long long flow=0,f; for(long long i=cur[now];i!=-1;i=e[i].next){ cur[now]=i; if(deep[e[i].n]==deep[now]+1 && (f=dfs(e[i].n,t, min(lim,e[i].v) ))){ flow+=f; lim-=f; e[i].v-=f; e[i^1].v+=f; if(!lim) break; } } return flow; } void dinic(long long s,long long t){ while(bfs(s,t)){ maxflow+=dfs(s,t,inf); } } }g; int main(){ in(n);in(m);in(k); g.init(); For(i,1,n){ g.push(0,i,1); g.push(i,0,0); } For(i,1,m){ g.push(i+n,n+m+1,1); g.push(n+m+1,n+i,0); } For(i,1,k){ in(x);in(y); g.push(x,y+n,1); g.push(y+n,x,0); } g.dinic(0,n+m+1); o(g.maxflow); return 0; }