zoukankan      html  css  js  c++  java
  • 洛谷P3386 【模板】二分图匹配

    传送门

    板子,直接用dinic

     1 //minamoto
     2 #include<iostream>
     3 #include<cstdio>
     4 #include<cstring>
     5 #include<queue>
     6 #define inf 0x3f3f3f3f
     7 using namespace std;
     8 #define getc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
     9 char buf[1<<21],*p1=buf,*p2=buf;
    10 inline int read(){
    11     #define num ch-'0'
    12     char ch;bool flag=0;int res;
    13     while(!isdigit(ch=getc()))
    14     (ch=='-')&&(flag=true);
    15     for(res=num;isdigit(ch=getc());res=res*10+num);
    16     (flag)&&(res=-res);
    17     #undef num
    18     return res;
    19 }
    20 const int N=2005,M=2100005;
    21 int ver[M],Next[M],head[N],edge[M],tot=1;
    22 int dep[N],cur[N],s,t;
    23 int n,m,k;
    24 queue<int> q;
    25 inline void add(int u,int v,int e){
    26     ver[++tot]=v,Next[tot]=head[u],head[u]=tot,edge[tot]=e;
    27     ver[++tot]=u,Next[tot]=head[v],head[v]=tot,edge[tot]=0;
    28 }
    29 bool bfs(){
    30     memset(dep,-1,sizeof(dep));
    31     while(!q.empty()) q.pop();
    32     for(int i=s;i<=t;++i) cur[i]=head[i];
    33     q.push(s),dep[s]=0;
    34     while(!q.empty()){
    35         int u=q.front();q.pop();
    36         for(int i=head[u];i;i=Next[i]){
    37             int v=ver[i];
    38             if(dep[v]<0&&edge[i]){
    39                 dep[v]=dep[u]+1,q.push(v);
    40                 if(v==t) return true;
    41             }
    42         }
    43     }
    44     return false;
    45 }
    46 int dfs(int u,int limit){
    47     if(!limit||u==t) return limit;
    48     int flow=0,f;
    49     for(int i=cur[u];i;i=Next[i]){
    50         int v=ver[i];cur[u]=i;
    51         if(dep[v]==dep[u]+1&&(f=dfs(v,min(limit,edge[i])))){
    52             flow+=f,limit-=f;
    53             edge[i]-=f,edge[i^1]+=f;
    54             if(!limit) break;
    55         }
    56     }
    57     return flow;
    58 }
    59 int dinic(){
    60     int flow=0;
    61     while(bfs()) flow+=dfs(s,inf);
    62     return flow;
    63 }
    64 int main(){
    65     n=read(),m=read(),k=read();
    66     s=0,t=n+m+1;
    67     for(int i=1;i<=n;++i) add(s,i,1);
    68     for(int i=n+1;i<=n+m;++i) add(i,t,1);
    69     for(int i=1;i<=k;++i){
    70         int u=read(),v=read();
    71         if(v>m) continue;
    72         add(u,v+n,1);
    73     }
    74     printf("%d
    ",dinic());
    75     return 0;
    76 }
  • 相关阅读:
    UDP最大传输字节
    [bzoj3994] [SDOI2015]约数个数和
    [bzoj3529] [Sdoi2014]数表
    [bzoj3309] DZY Loves Math
    [bzoj2693] jzptab
    [bzoj4407] 于神之怒加强版
    [bzoj3688] 折线统计
    [bzoj2301] [HAOI2011]Problem b
    [bzoj2820] YY的GCD
    [bzoj4559] [JLoi2016]成绩比较
  • 原文地址:https://www.cnblogs.com/bztMinamoto/p/9509694.html
Copyright © 2011-2022 走看看