【luogu P1402 酒店之王】 题解

题目链接:https://www.luogu.org/problemnew/show/P1402

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e6 + 10;
const int inf = 1e9;
int n, p, q, s, t, deep[maxn], maxflow;
struct edge{
    int flow, next, to;
}e[maxn<<2];
int head[maxn], cnt = -1;
queue<int> q1;
void add(int u, int v, int w)
{
    e[++cnt].flow = w; e[cnt].next = head[u]; e[cnt].to = v; head[u] = cnt;
    e[++cnt].flow = 0; e[cnt].next = head[v]; e[cnt].to = u; head[v] = cnt;
}
bool bfs(int s, int t)
{
    memset(deep, 0x7f, sizeof(deep));
    while(!q1.empty()) q1.pop();
    q1.push(s); deep[s] = 0;
    while(!q1.empty())
    {
        int now = q1.front(); q1.pop();
        for(int i = head[now]; i != -1; i = e[i].next)
        {
            if(deep[e[i].to] > inf && e[i].flow)
            {
                deep[e[i].to] = deep[now] + 1;
                q1.push(e[i].to);
            }
        }
    }
    if(deep[t] < inf) return true;
    else return false;
}
int dfs(int now, int t, int limit)
{
    if(!limit || now == t) return limit;
    int flow = 0, f;
    for(int i = head[now]; i != -1; i = e[i].next)
    {
        if(deep[e[i].to] == deep[now] + 1 && (f = dfs(e[i].to, t, min(e[i].flow, limit))))
        {
            flow += f;
            limit -= f;
            e[i].flow -= f;
            e[i^1].flow += f;
            if(!limit) break;
        }
    }
    return flow;
}
void Dinic(int s, int t)
{
    while(bfs(s, t))
    maxflow += dfs(s, t, inf);
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d%d",&n,&p,&q);
    s = 1, t = n + n + p + q + 2;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= p; j++)
        {
            int u;
            scanf("%d",&u);
            if(u == 1)
            {
                add(j + n + n + 1, i + 1, 1);
            }
        }
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= q; j++)
        {
            int u;
            scanf("%d",&u);
            if(u == 1)
            {
                add(i + n + 1, j + n + n + p + 1, 1);
            }
        }
    for(int i = 1; i <= n; i++)
    add(i + 1, i + n + 1, 1);
    for(int i = 1; i <= p; i++)
    add(s, i + n + n + 1, 1);
    for(int i = 1; i <= q; i++)
    add(i + n + n + p + 1, t, 1);
    Dinic(s, t);
    printf("%d",maxflow);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/MisakaAzusa/p/9447474.html