「网络流 24 题」搭配飞行员 网络流做法

套EK模板

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <map>
#include <cmath>
#include <algorithm>
#define inf 0x3f3f3f3f
#define SI(a) scanf("%d",&a)
#define set0(a) memset(a,0,sizeof(a))
#define setMo(a) memset(a,-1,sizeof(a))
typedef long long ll;
const int mod = 998244353;
const int maxn = 2e5+10;
using namespace std;

struct Edge{
    
    
    int from,to,cap,flow;
    Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){
    
    }
};

//基于BFS的增广路算法
int n,m,u,v,s,t;
vector<Edge>edges;//边集
vector<int>G[maxn];//邻接表
int a[maxn];//可改进量
int p[maxn];//最短路上p的入弧编号
int vis[maxn];
void init(int n)
{
    
    
    for(int i = 0;i <= n+3;i++)
        G[i].clear();
    edges.clear();
}

void AddEdge(int from,int to,int cap)
{
    
    
    edges.push_back(Edge(from,to,cap,0));
    edges.push_back(Edge(to,from,0,0));
    m = edges.size();
    G[from].push_back(m-2);
    G[to].push_back(m-1);
}

int MaxFlow(int s,int t)
{
    
    
    int flow = 0;
    for(;;)
    {
    
    
        set0(a);
        queue<int>q;
        q.push(s);
        a[s] = inf;
        while(!q.empty())
        {
    
    
            int x = q.front();
            q.pop();
            for(int i = 0;i < (int)G[x].size();i++)
            {
    
    
                Edge &e = edges[G[x][i]];
                //cout<<2<<endl;
                if(!a[e.to]&&e.cap > e.flow){
    
    
                    p[e.to] = G[x][i];
                    a[e.to] = min(a[x],e.cap-e.flow);
                    q.push(e.to);
                    //cout<<1<<endl;
                }
            }
            if(a[t])break;
        }
        if(!a[t])break;
        for(int u = t;u != s;u = edges[p[u]].from)
        {
    
    
            edges[p[u]].flow += a[t];
            edges[p[u]^1].flow -= a[t];
        }
        flow += a[t];
    }
    return flow;
}


int main()
{
    
    
        while(cin>>n>>m){
    
    
        s=0,t=n+1;
        //cout<<s<<" "<<t<<endl;
        init(t);
        set0(vis);
        int u,v;
        while(cin>>u>>v)
        {
    
    
            AddEdge(u,v,1);//能搭配的正副驾驶员加边
            if(!vis[u])
            {
    
    AddEdge(s,u,1);vis[u] = 1;}
            if(!vis[v])
            {
    
    AddEdge(v,t,1);vis[v] = 1;}
        }
        cout<<MaxFlow(s,t)<<endl;
        }
}

猜你喜欢

转载自blog.csdn.net/qq_42937838/article/details/105495337