看到了一篇有趣的博客:http://blog.csdn.net/dark_scope/article/details/8880547
#include<algorithm> #include<iostream> #include<cstdlib> #include<cstdio> #define ma 1005 bool used[ma]; int pre[1000005],fir[1000005],nxt[1000005],to[1000005],n,m,e=0; using namespace std; int get() { int ans=0,f=1;char ch=getchar(); while(!isdigit(ch)) {if(ch=='-') f=-1;ch=getchar();} while(isdigit(ch)) {ans=ans*10+ch-'0';ch=getchar();} return ans*f; } inline void add(int a,int b) { nxt[++e]=fir[a];fir[a]=e;to[e]=b; } bool find(int x) { for(register int i=fir[x];i;i=nxt[i]) if(!used[to[i]]) { used[to[i]]=1; if(!pre[to[i]]||find(pre[to[i]])) { pre[to[i]]=x; return 1; } } return 0; } int main() { n=get(),m=get(); int u,v,e=get(),ans=0; for(register int i=1;i<=e;i++) { u=get();v=get(); if(u>n||v>m) continue; add(u,v); } for(register int i=1;i<=n;i++) { if(find(i)) ans++; fill(used,used+m+1,0); } printf("%d",ans); return 0; }