最大流+EK算法在于建图

点击打开链接
//建立一个超级源点和一个超级汇点,将cows与超级源点相连,容量为1
//stalls与汇点连接,容量为1,然后cows与stalls连接,容量为1
//求出最大流即可。
//  main.cpp
//  test
//  Created by 吴有堃 on 2017/9/11
//  Copyright © 2017年 吴有堃. All rights reserved
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <queue>
#include <vector>
#include <map>
#define LL long long
#define inf 0x3f3f3f3f
#define mod 1e9+7
using namespace std;
const int maxn=505;
LL cap[maxn][maxn],flow[maxn][maxn],rest[maxn];
int snode,tnode,pre[maxn],vis[maxn];
bool BFS_Path(int m)//augmenting path
{
    memset(vis, 0, sizeof(vis));
    queue<int>Q;
    int u=0,v=0;
    u=snode; pre[u]=u;
    rest[u]=inf;vis[u]=1;
    Q.push(u);
    while (!Q.empty()) {
        u=Q.front(); Q.pop();
        for(v=0;v<=m;v++){
            if(!vis[v]&&flow[u][v]<cap[u][v]){
                pre[v]=u;vis[v]=1;
                rest[v]=min(rest[u],cap[u][v]-flow[u][v]);
                if(v==tnode) return true; // find augment path
                Q.push(v);
            }
        }
    }
    return false;//no augment path
}
LL max_flow(int s, int t, int m)
{
    snode=s;tnode=t;
    LL ans=0;
    while (BFS_Path(m)) {
        ans+=rest[t];
        int v=t;
        while (v!=s) {
            int u=pre[v];
            flow[u][v]+=rest[t];
            flow[v][u]-=rest[t];
            v=u;
        }
    }
    return ans;
}
int main()
{
    int N=0,M=0;
    while (scanf("%d %d",&N,&M)!=EOF) {
        memset(cap, 0, sizeof(cap));
        memset(flow, 0, sizeof(flow));
        memset(pre, 0, sizeof(pre));
        memset(rest, 0, sizeof(rest));
        int s=0,t=N+M+1,num=0,a=0;
        for(int i=1;i<=N;i++){
            scanf("%d",&num);
            cap[s][i]=1; //源点s与每头牛链接;
            while (num--) {
                scanf("%d",&a);
                cap[i][N+a]=1;//每头牛和对应的stall链接
            }
        }
        for(int i=1;i<=M;i++){//每个stall与汇点t相联
            cap[i+N][t]=1;
        }
        cout<<max_flow(s,t,t)<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值