Algoogle

Algorithm for Programming Contest

PKU 1274 The Perfect Stall

Category: PKU Tag: bipartite-matching, max-flow

The Perfect Stall

問題概要


N頭の牛それぞれについて, 牛乳を出すことのできる牛舎の集合が与えられる.
牛と牛舎をうまく割り当てた時の牛乳を出すことのできる牛の数の最大を求めよ.

解法


2部マッチングやるだけ

コード


(1274.cpp) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

const int inf = 1e9;
struct edge{int to, cap, rev;};
vector<edge> E[512];

int N, M;
int level[512], iter[512];

void add_edge(int from, int to, int cap){
    E[from].push_back(edge{to, cap, int(E[to].size())});
    E[to].push_back(edge{from, 0, int(E[from].size()-1)});
}

void bfs(int s){
    memset(level, -1, sizeof(level));
    queue<int> que;
    level[s] = 0;
    que.push(s);
    while(!que.empty()){
        int v = que.front(); que.pop();
        for(int i = 0; i < E[v].size(); i++){
            edge &e = E[v][i];
            if(e.cap > 0 and level[e.to] < 0) {
                level[e.to] = level[v]+1;
                que.push(e.to);
            }
        }
    }
}

int dfs(int v, int t, int f){
    if(v == t) return f;
    for(int &i = iter[v]; i < E[v].size(); i++){
        edge &e = E[v][i];
        if(e.cap > 0 and level[e.to] > level[v]){
            int d = dfs(e.to, t, min(f, e.cap));
            if(d > 0){
                e.cap -= d;
                E[e.to][e.rev].cap += d;
                return d;
            }
        }
    }
    return 0;
}

int dinic(int s, int t){
    int flow = 0;
    while(1){
        bfs(s);
        if(level[t]< 0) return flow;
        memset(iter, 0, sizeof(iter));
        int f;
        while((f = dfs(s, t, inf)) > 0) flow += f;
    }
}


void init(){
    for(int i = 0; i < 512; i++)
        E[i].clear();
}
int main(){
    while(~scanf("%d%d", &N, &M)){
        init();
        int s = N+M, t = N+M+1;
        for(int i = 0; i < N; i++){
            add_edge(s, i, 1);
            int m; scanf("%d", &m);
            for(int j = 0; j < m; j++){
                int n; scanf("%d", &n);
                add_edge(i, N+n-1, 1);
            }
        }
        for(int i = 0; i < M; i++)
            add_edge(N+i,t,1);
        printf("%d\n", dinic(s,t));
    }
}

Comments