其他分享
首页 > 其他分享> > 网络流24题-圆桌问题

网络流24题-圆桌问题

作者:互联网

二分图匹配的问题

#include<iostream>
#include<queue>
#include<string>
#include<cstring>
#include <algorithm>
using namespace std;
const int N = 420 + 10;
const int M = (150*270+N)*2 + 10;
const int INF = 0x3f3f3f3f;

int n,m,s,t;
int e[M],ne[M],h[N],w[M],idx;
int deepth[N],gap[N];

void add(int a,int b,int c)
{
    e[idx] = b,ne[idx] = h[a],w[idx] = c,h[a] = idx++;
    swap(a,b),c = 0;
    e[idx] = b,ne[idx] = h[a],w[idx] = c,h[a] = idx++;

}

void bfs()
{
    queue<int>q;
    memset(deepth,-1,sizeof(deepth));
    memset(gap,0,sizeof(gap));
    q.push(t);
    deepth[t] = 0;
    gap[0]++;
    while(q.size())
    {
        int a = q.front();
        q.pop();
        for(int i = h[a];~i;i = ne[i])
        {
            int j = e[i];
            if(deepth[j] == -1)
            {
                deepth[j] = deepth[a] + 1;
                gap[deepth[j]]++;
                q.push(j);
            }
        }
    }
}
int dfs(int now,int flow)
{
    if(now == t)
        return flow;
    int nowflow = 0;
    for(int i = h[now];~i;i = ne[i])
    {
        int j = e[i];
        if(w[i]&&deepth[j] == deepth[now] - 1)
        {
            int k = dfs(j,min(w[i],flow - nowflow));
            w[i]-=k,w[i^1]+=k,nowflow+=k;
            if(flow == nowflow)
                return flow;
        }
    }
    gap[deepth[now]]--;
    if(!gap[deepth[now]])
        gap[s] = n+2;
    deepth[now]++;
    gap[deepth[now]]++;
    return nowflow;
}
int ISAP()
{
    bfs();
    int ans = 0;
    while(gap[s] < n)
    {
        ans+=dfs(s,INF);
    }
    return ans;
}
int main()
{
    memset(h,-1,sizeof h);
    idx = 0;
    cin >> m >> n;
    s = 0,t = N-1;
    int tot = 0;
    for(int i = 1;i<=m;i++)
    {
        int x;
        cin >> x;
        tot +=x;
        add(s,i,x);
    }
    for(int i = 1 + m;i<=n+m;i++)
    {
        int x;
        cin >> x;
        add(i,t,x);
    }
    for(int i = 1;i<=m;i++)
        for(int j = 1+m;j<=n+m;j++)
            add(i,j,1);
    if(ISAP()!=tot)
        cout << 0 << endl;
    else
    {
        cout << 1 << endl;
        for(int a = 1;a<=m;a++)
        {
            for(int i = h[a];~i;i = ne[i])
            {
                int j = e[i];
                if(j>m&&j<=n+m&&!w[i])
                {
                    cout << j-m<<" ";
                }
            }   
            cout << endl;
        }


    }
    return 0;
}

 

标签:24,idx,int,网络,gap,deepth,++,now,圆桌
来源: https://www.cnblogs.com/ignorance/p/14057256.html