二分图的最大匹配(模板)

传送门:https://www.luogu.org/problem/P3386

已经加入极其简单的当前弧优化 

 

  1 #include<bits/stdc++.h>
  2 using namespace std;
  3 int n,m,bian,s,t;
  4 int dep[6000001];
  5 int inque[6000001];
  6 int cur[6000001];
  7 int maxflow=0;
  8 struct edge{
  9     int to,nxt,flow;
 10 }e[6000001];int tot=-1;
 11 int first[6000001];
 12 const int inf=0x3f3f3f3f;
 13 inline int kd()
 14 {
 15     int x=0,f=1;char ch=getchar();
 16     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
 17     while(ch>='0'&&ch<='9'){x=x*10+(ch^48);ch=getchar();}
 18     return x*f;
 19 }
 20 inline void add_edge(int a,int b,int c)
 21 {
 22     e[++tot].to=b;
 23     e[tot].flow=c;
 24     e[tot].nxt=first[a];
 25     first[a]=tot;
 26 }
 27 bool bfs()
 28 {
 29     for(register int i=0;i<=n+m+2;i++)cur[i]=first[i],inque[i]=false,dep[i]=0x3f3f3f3f;
 30     dep[s]=0;
 31     queue<int>q;
 32     q.push(s);
 33     while(q.empty()==false)
 34     {
 35         int now=q.front();
 36         q.pop();
 37         inque[now]=false;
 38         for(int i=first[now];i!=-1;i=e[i].nxt)
 39         {
 40             int to=e[i].to;
 41             if(dep[now]+1<dep[to]&&e[i].flow!=0)
 42             {
 43                 dep[to]=dep[now]+1;
 44                 if(inque[to]==false)
 45                 {
 46                     inque[to]=true;
 47                     q.push(to);
 48                 }
 49             }
 50         }
 51     }
 52     if(dep[t]==0x3f3f3f3f)return false;
 53     return true;
 54 }
 55 int dfsl(int now,int nowflow)
 56 {
 57     int rlow=0;
 58     if(now==t)return nowflow;
 59     for(int i=cur[now];i!=-1;i=e[i].nxt)
 60     {
 61         cur[now]=i;
 62         if(dep[now]+1==dep[e[i].to]&&e[i].flow!=0)
 63         {
 64             if(rlow=dfsl(e[i].to,min(nowflow,e[i].flow)))
 65             {
 66                 e[i].flow-=rlow;
 67                 e[i^1].flow+=rlow;
 68                 return rlow;
 69             }
 70         }
 71     }
 72     return 0;
 73 }
 74 void dinic()
 75 {
 76     int lowflow;
 77     while(bfs()){
 78         while(lowflow=dfsl(s,inf)){
 79             maxflow+=lowflow;
 80         }
 81     }
 82     return;
 83 }
 84 int main()
 85 {
 86     memset(first,-1,sizeof(first));
 87     n=kd(),m=kd(),bian=kd(),s=0,t=m+n+1;
 88     for(int i=1;i<=n;i++)
 89     {
 90         add_edge(s,i,1);
 91         add_edge(i,s,0);
 92     }
 93     for(int i=1;i<=bian;i++)
 94     {
 95         int a=kd(),b=kd();
 96         if(a>n||b>m)continue;
 97         add_edge(a,b+n,1);
 98         add_edge(b+n,a,0);
 99     }
100     for(int i=1;i<=m;i++)
101     {
102         add_edge(i+n,t,1);
103         add_edge(t,i+n,0);
104     }
105     dinic();
106     cout<<maxflow<<endl;
107 }

 

posted @ 2019-11-05 17:57  nono_ttaa  阅读(223)  评论(0编辑  收藏  举报