zoukankan      html  css  js  c++  java
  • 猪(最大流,建图)

    题意

    思路

    这道题的建图是这样的,每个顾客作为流网络中的点。并设立虚拟源点(S)和虚拟汇点(T)

    对于一个顾客,考察每个他能开启的猪圈,如果该猪圈之前没用过,则源点(S)向他连容量是该猪圈起始猪数的边。如果该猪圈之前用过,则从上一次用这个猪圈的顾客向他连一条容量是(infty)的边。

    跑一遍最大流即可。

    这道题建图特别经典,但是我还没想明白为什么这么建,待补

    代码

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <queue>
    
    using namespace std;
    
    const int N = 110, M = 20210, inf = 1e8;
    
    int n, m, S, T;
    int h[N], e[M], ne[M], f[M], idx;
    int d[N], cur[N];
    int w[1010], last[1010];
    
    void add(int a, int b, int c)
    {
        e[idx] = b, f[idx] = c, ne[idx] = h[a], h[a] = idx ++;
        e[idx] = a, f[idx] = 0, ne[idx] = h[b], h[b] = idx ++;
    }
    
    bool bfs()
    {
        memset(d, -1, sizeof(d));
        queue<int> que;
        que.push(S);
        d[S] = 0, cur[S] = h[S];
        while(que.size()) {
            int t = que.front();
            que.pop();
            for(int i = h[t]; ~i; i = ne[i]) {
                int ver = e[i];
                if(d[ver] == -1 && f[i]) {
                    d[ver] = d[t] + 1;
                    cur[ver] = h[ver];
                    if(ver == T) return true;
                    que.push(ver);
                }
            }
        }
        return false;
    }
    
    int find(int u, int limit)
    {
        if(u == T) return limit;
        int flow = 0;
        for(int i = cur[u]; ~i && flow < limit; i = ne[i]) {
            cur[u] = i;
            int ver = e[i];
            if(d[ver] == d[u] + 1 && f[i]) {
                int t = find(ver, min(f[i], limit - flow));
                if(!t) d[ver] = -1;
                f[i] -= t, f[i ^ 1] += t, flow += t;
            }
        }
        return flow;
    }
    
    int dinic()
    {
        int res = 0, flow;
        while(bfs()) {
            while(flow = find(S, inf)) {
                res += flow;
            }
        }
        return res;
    }
    
    int main()
    {
        scanf("%d%d", &m, &n);
        memset(h, -1, sizeof(h));
        S = 0, T = n + 1;
        for(int i = 1; i <= m; i ++) scanf("%d", &w[i]);
        for(int i = 1; i <= n; i ++) {
            int a;
            scanf("%d", &a);
            while(a --) {
                int id;
                scanf("%d", &id);
                if(!last[id]) add(S, i, w[id]);
                else add(last[id], i, inf);
                last[id] = i;
            }
            int b;
            scanf("%d", &b);
            add(i, T, b);
        }
        printf("%d
    ", dinic());
        return 0;
    }
    
  • 相关阅读:
    阅读文献的三大问题:坐不住,记不住,想不开
    C++之vector模板类
    C++之string类
    算法学习(1)枚举法求运算符
    二叉树(4)非递归法遍历二叉树
    二叉树(3):对二叉树数的操作
    Pascal's Triangle,Pascal's Triangle II
    Next Permutation
    Permutations,Permutations II,Combinations
    Majority Element,Majority Element II
  • 原文地址:https://www.cnblogs.com/miraclepbc/p/14404327.html
Copyright © 2011-2022 走看看