「网络流 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;
        }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值