POJ-3281 Dining

题目链接:POJ-3281 Dining

题意

有$N$头牛,$F$个食物,$D$个饮料,每头牛有一定的喜好,只喜欢某几个食物和饮料,一头牛必须同时获得一个食物和一个饮料才能满足,问至多有多少头牛可以获得满足。


思路

流网络建图:

一头牛拆分成两个点$u$和$v$,这头牛喜欢的食物向$u$连边,$u$向$v$连边,$v$向这头牛喜欢的饮料连边;

源点$s$向每个食物连边,每个饮料向汇点$t$连边,所有边容量都是1。

最大流即为答案。


代码实现

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using std::queue;
const int INF = 1 << 29, N = 1000, M = 30010;
int head[N], ver[M], edge[M], Next[M], d[N];
int s, t, tot, maxflow;
queue<int> q;
void add(int x, int y, int z) {
    ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot;
    ver[++tot] = x, edge[tot] = 0, Next[tot] = head[y], head[y] = tot;
}
bool bfs() {
    memset(d, 0, sizeof(d));
    while (q.size()) q.pop();
    q.push(s); d[s] = 1;
    while (q.size()) {
        int x = q.front(); q.pop();
        for (int i = head[x]; i; i = Next[i]) {
            if (edge[i] && !d[ver[i]]) {
                q.push(ver[i]);
                d[ver[i]] = d[x] + 1;
                if (ver[i] == t) return true;
            }
        }
    }
    return false;
}
int dinic(int x, int flow) {
    if (x == t) return flow;
    int rest = flow, k;
    for (int i = head[x]; i && rest; i = Next[i]) {
        if (edge[i] && d[ver[i]] == d[x] + 1) {
            k = dinic(ver[i], std::min(rest, edge[i]));
            if (!k) d[ver[i]] = 0;
            edge[i] -= k;
            edge[i^1] += k;
            rest -= k;
        }
    }
    return flow - rest;
}

int main() {
    int nn, fo, dr;
    while (~scanf("%d %d %d", &nn, &fo, &dr)) {
        memset(head, 0, sizeof(head));
        s = 0, t = 2 * nn + fo + dr + 1, tot = 1, maxflow = 0;
        for (int i = 1; i <= fo; i++) add(0, i, 1);
        for (int i = fo + 2 * nn + 1; i <= fo + 2 * nn + dr; i++) add(i, fo + 2 * nn + dr + 1, 1);
        for (int i = fo + 1; i <= fo + nn; i++) add(i, i + nn, 1);
        for (int i = 1; i <= nn; i++) {
            int fi, di, tpe;
            scanf("%d %d", &fi, &di);
            for (int j = 0; j < fi; j++) {
                scanf("%d", &tpe);
                add(tpe, fo + i, 1);
            }
            for (int j = 0; j < di; j++) {
                scanf("%d", &tpe);
                add(fo + i + nn, tpe + fo + 2 * nn, 1);
            }
        }
        while (bfs()) maxflow += dinic(s, INF);
        printf("%d\n", maxflow);
    }
    return 0;
}
View Code

 

posted @ 2019-08-12 22:06  _kangkang  阅读(423)  评论(0编辑  收藏  举报