太空飞行计划问题(最小割,最大权闭合图,网络流24题)

题意

\(n\)个实验,和\(m\)种器材。

每个实验都需要若干种器材,做一个实验可以获得\(p_i\)的收益,配置一个器材需要花费\(c_i\)

问做哪些实验,可以获得最大收益。

思路

最大获利的推广版,最大权闭合图模板题

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <sstream>

using namespace std;

const int N = 110, M = (2500 + N) * 2, inf = 1e8;

int n, m, S, T;
int h[N], e[M], ne[M], f[M], idx;
int cur[N], d[N];
bool st[N];

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;
}

void dfs(int u)
{
    st[u] = true;
    for(int i = h[u]; ~i; i = ne[i]) {
        int j = e[i];
        if(st[j] || !f[i]) continue;
        dfs(j);
    }
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof(h));
    S = 0, T = n + m + 1;
    getchar();
    int sum = 0;
    for(int i = 1; i <= n; i ++) {
        int c, id;
        string line;
        getline(cin, line);
        stringstream ssin(line);
        ssin >> c;
        add(S, i, c);
        while(ssin >> id) add(i, id + n, inf);
        sum += c;
    }
    for(int i = 1; i <= m; i ++) {
        int c;
        scanf("%d", &c);
        add(n + i, T, c);
    }
    int ans = dinic();
    dfs(0);
    for(int i = 1; i <= n; i ++) {
        if(st[i]) printf("%d ", i);
    }
    printf("\n");
    for(int i = 1; i <= m; i ++) {
        if(st[i + n]) printf("%d ", i);
    }
    printf("\n");
    printf("%d\n", sum - ans);
    return 0;
}
posted @ 2021-02-17 16:00  pbc的成长之路  阅读(60)  评论(0编辑  收藏  举报