Loj #6000. 「网络流 24 题」搭配飞行员
题目链接:https://loj.ac/problem/6000
先来贴一发模板,然后去刷题
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 const int MAXN=1005; 5 const int MAXM=3005; 6 const int INF=0x3f3f3f3f; 7 struct Edge 8 { 9 int to,next,cap,flow; 10 }edge[MAXM]; 11 int tol,head[MAXN]; 12 int gap[MAXN],dep[MAXN],pre[MAXN],cur[MAXN]; 13 void init() 14 { 15 tol=0; 16 memset(head,-1,sizeof(head)); 17 } 18 void addedge(int u,int v,int w,int rw=0) 19 { 20 edge[tol].to=v; 21 edge[tol].cap=w; 22 edge[tol].next=head[u]; 23 edge[tol].flow=0; 24 head[u]=tol++; 25 edge[tol].to=u; 26 edge[tol].cap=rw; 27 edge[tol].next=head[v]; 28 edge[tol].flow=0; 29 head[v]=tol++; 30 } 31 int sap(int st,int ed,int N) 32 { 33 memset(gap,0,sizeof(gap)); 34 memset(dep,0,sizeof(dep)); 35 memcpy(cur,head,sizeof(head)); 36 int u=st; 37 pre[u]=-1; 38 gap[0]=N; 39 int ans=0; 40 while(dep[st]<N) 41 { 42 if(u==ed) 43 { 44 int Min=INF; 45 for(int i=pre[u];i!=-1;i=pre[edge[i^1].to]) 46 if(Min>edge[i].cap-edge[i].flow) 47 Min=edge[i].cap-edge[i].flow; 48 for(int i=pre[u];i!=-1;i=pre[edge[i^1].to]) 49 { 50 edge[i].flow+=Min; 51 edge[i^1].flow-=Min; 52 } 53 u=st; 54 ans+=Min; 55 continue; 56 } 57 bool flag=0; 58 int v; 59 for(int i=cur[u];i!=-1;i=edge[i].next) 60 { 61 v=edge[i].to; 62 if(edge[i].cap-edge[i].flow && dep[v]+1==dep[u]) 63 { 64 flag=1; 65 cur[u]=pre[v]=i; 66 break; 67 } 68 } 69 if(flag) 70 { 71 u=v; 72 continue; 73 } 74 int Min=N; 75 for(int i=head[u];i!=-1;i=edge[i].next) 76 if(edge[i].cap-edge[i].flow && dep[edge[i].to]<Min) 77 { 78 Min=dep[edge[i].to]; 79 cur[u]=i; 80 } 81 gap[dep[u]]--; 82 if(!gap[dep[u]])return ans; 83 dep[u]=Min+1; 84 gap[dep[u]]++; 85 if(u!=st)u=edge[pre[u]^1].to; 86 } 87 return ans; 88 } 89 int main() 90 { 91 ios_base::sync_with_stdio(false); 92 cin.tie(0); 93 int n,m; 94 init(); 95 cin>>n>>m; 96 int a,b; 97 for(int i=1;i<=m;i++){ 98 addedge(0,i,1); 99 } 100 for(int i=m+1;i<=n;i++){ 101 addedge(i,n+1,1); 102 } 103 while(cin>>a>>b){ 104 addedge(a,b,1); 105 } 106 int d=sap(0,n+1,n+2); 107 cout<<d<<endl; 108 return 0; 109 }