けんちょんの競プロ精進記録

競プロの精進記録や小ネタを書いていきます

yukicoder No.2713 Just Solitaire

とても典型的で教育的な「燃やす埋める」の練習問題!

問題概要

 N 枚のカード  1, 2, \dots, N があり、カード  i を使用するには  A_{i} だけコストがかかる。

一方、いくつかのカードを使用した場合、次の  M 種類のボーナス  1, 2, \dots, M があり、ボーナス  j をクリアすると  B_{j} だけスコアを獲得できる。

  • ボーナス  j のクリア条件:カード  C_{j, 1}, C_{j, 2}, \dots, C_{j, K_{j}} をすべて使用すること

獲得スコアから消費コストを引いた値の最大値を求めよ。

制約

  •  1 \le N, M \le 100

考えたこと:「燃やす埋める」とは

典型的な「燃やす埋める」の問題ですね。「燃やす埋める」とその一般化については、次の記事に詳しく書きました。

drken1215.hatenablog.com

まず「燃やす埋める」でできることを確認しておきましょう。「燃やす埋める」では、次のようなコストを表現できます。


 N 個の変数  x_{0}, x_{1}, \dots, x_{N-1} があって、それぞれ 0 または 1 の値を取るとします。以下のようにコストが加算されるとき、その総和を最小化したいとします。

1 変数についてのコスト

  •  x_{i} = 0 のとき、コスト  F_{i} が加算される
  •  x_{i} = 1 のとき、コスト  T_{i} が加算される

2 変数についてのコスト

  •  x_{i} = 1 かつ  x_{j} = 0 のとき、コスト  C_{i, j} が加算される

今回の問題をこのフレームワークに当てはめてみましょう。ただし。「獲得スコア - 消費スコアの最大値」を「消費スコア - 獲得スコアの最小値」と読み替えます。

 

「燃やす埋める」への定式化

まず、以下の 2 種類の 0-1 変数を定義します。

 x_{i} = \left\{
\begin{array}{ll}
1 & (カード i を使うとき)\\
0 & (使わないとき)
\end{array}
\right.
 y_{j} = \left\{
\begin{array}{ll}
1 & (ボーナス j を満たすとき) \\
0 & (使わないとき)
\end{array}
\right.

そうすると、今回の問題のコストは次のように解釈できます。


1 変数  x_{i} についてのコスト

  •  x_{i} = 0 のとき、コスト 0 が加算される
  •  x_{i} = 1 のとき、コスト  A_{i} が加算される

1 変数  y_{i} についてのコスト

  •  y_{j} = 0 のとき、コスト 0 が加算される
  •  y_{j} = 1 のとき、コスト  - B_{j} が加算される

2 変数についてのコスト

ボーナス  j にカード  i が含まれるとき、

  •  x_{i} = 0 かつ  y_{j} = 1 のとき、コスト  \infty が加算される (禁止なので)

ここまで定式化できていれば、「燃やす埋める」をフローに落とし込んで解くことができます。フローに落とす方法については、上の記事を参照。

計算量は  O((N + M)^{3}) となります。

 

コード

#include <bits/stdc++.h>
using namespace std;

// 2-variable submodular optimization
template<class COST> struct TwoVariableSubmodularOpt {
    // constructors
    TwoVariableSubmodularOpt() : N(2), S(0), T(0), OFFSET(0) {}
    TwoVariableSubmodularOpt(int n, COST inf = 0)
    : N(n), S(n), T(n + 1), OFFSET(0), INF(inf), list(n + 2) {}
    
    // initializer
    void init(int n, COST inf = 0) {
        N = n, S = n, T = n + 1;
        OFFSET = 0, INF = inf;
        list.assign(N + 2, Edge());
        pos.clear();
    }

    // add 1-Variable submodular functioin
    void add_single_cost(int xi, COST false_cost, COST true_cost) {
        assert(0 <= xi && xi < N);
        if (false_cost >= true_cost) {
            OFFSET += true_cost;
            add_edge(S, xi, false_cost - true_cost);
        } else {
            OFFSET += false_cost;
            add_edge(xi, T, true_cost - false_cost);
        }
    }
    
    // add "project selection" constraint
    // xi = T, xj = F: strictly prohibited
    void add_psp_constraint(int xi, int xj) {
        assert(0 <= xi && xi < N);
        assert(0 <= xj && xj < N);
        add_edge(xi, xj, INF);
    }
    
    // add "project selection" penalty
    // xi = T, xj = F: cost C
    void add_psp_penalty(int xi, int xj, COST C) {
        assert(0 <= xi && xi < N);
        assert(0 <= xj && xj < N);
        assert(C >= 0);
        add_edge(xi, xj, C);
    }
    
    // add both True profit
    // xi = T, xj = T: profit P (cost -P)
    void add_both_true_profit(int xi, int xj, COST P) {
        assert(0 <= xi && xi < N);
        assert(0 <= xj && xj < N);
        assert(P >= 0);
        OFFSET -= P;
        add_edge(S, xi, P);
        add_edge(xi, xj, P);
    }
    
    // add both False profit
    // xi = F, xj = F: profit P (cost -P)
    void add_both_false_profit(int xi, int xj, COST P) {
        assert(0 <= xi && xi < N);
        assert(0 <= xj && xj < N);
        assert(P >= 0);
        OFFSET -= P;
        add_edge(xj, T, P);
        add_edge(xi, xj, P);
    }
    
    // add general 2-variable submodular function
    // (xi, xj) = (F, F): A, (F, T): B
    // (xi, xj) = (T, F): C, (T, T): D
    void add_submodular_function(int xi, int xj, COST A, COST B, COST C, COST D) {
        assert(0 <= xi && xi < N);
        assert(0 <= xj && xj < N);
        assert(B + C >= A + D);  // assure submodular function
        OFFSET += A;
        add_single_cost(xi, 0, D - B);
        add_single_cost(xj, 0, B - A);
        add_psp_penalty(xi, xj, B + C - A - D);
    }
    
    // add all True profit
    // y = F: not gain profit (= cost is P), T: gain profit (= cost is 0)
    // y: T, xi: F is prohibited
    void add_all_true_profit(const vector<int> &xs, COST P) {
        assert(P >= 0);
        int y = (int)list.size();
        list.resize(y + 1);
        OFFSET -= P;
        add_edge(S, y, P);
        for (auto xi : xs) {
            assert(xi >= 0 && xi < N);
            add_edge(y, xi, INF);
        }
    }
    
    // add all False profit
    // y = F: gain profit (= cost is 0), T: not gain profit (= cost is P)
    // xi = T, y = F is prohibited
    void add_all_false_profit(const vector<int> &xs, COST P) {
        assert(P >= 0);
        int y = (int)list.size();
        list.resize(y + 1);
        OFFSET -= P;
        add_edge(y, T, P);
        for (auto xi : xs) {
            assert(xi >= 0 && xi < N);
            add_edge(xi, y, INF);
        }
    }
    
    // solve
    COST solve() {
        return dinic() + OFFSET;
    }
    
    // reconstrcut the optimal assignment
    vector<bool> reconstruct() {
        vector<bool> res(N, false), seen(list.size(), false);
        queue<int> que;
        seen[S] = true;
        que.push(S);
        while (!que.empty()) {
            int v = que.front();
            que.pop();
            for (const auto &e : list[v]) {
                if (e.cap && !seen[e.to]) {
                    if (e.to < N) res[e.to] = true;
                    seen[e.to] = true;
                    que.push(e.to);
                }
            }
        }
        return res;
    }
    
    // debug
    friend ostream& operator << (ostream& s, const TwoVariableSubmodularOpt &G) {
        const auto &edges = G.get_edges();
        for (const auto &e : edges) s << e << endl;
        return s;
    }
    
private:
    // edge class
    struct Edge {
        // core members
        int rev, from, to;
        COST cap, icap, flow;
        
        // constructor
        Edge(int r, int f, int t, COST c)
        : rev(r), from(f), to(t), cap(c), icap(c), flow(0) {}
        void reset() { cap = icap, flow = 0; }
        
        // debug
        friend ostream& operator << (ostream& s, const Edge& E) {
            return s << E.from << "->" << E.to << '(' << E.flow << '/' << E.icap << ')';
        }
    };
    
    // inner data
    int N, S, T;
    COST OFFSET, INF;
    vector<vector<Edge>> list;
    vector<pair<int,int>> pos;
    
    // add edge
    Edge &get_rev_edge(const Edge &e) {
        if (e.from != e.to) return list[e.to][e.rev];
        else return list[e.to][e.rev + 1];
    }
    Edge &get_edge(int i) {
        return list[pos[i].first][pos[i].second];
    }
    const Edge &get_edge(int i) const {
        return list[pos[i].first][pos[i].second];
    }
    vector<Edge> get_edges() const {
        vector<Edge> edges;
        for (int i = 0; i < (int)pos.size(); ++i) {
            edges.push_back(get_edge(i));
        }
        return edges;
    }
    void add_edge(int from, int to, COST cap) {
        if (!cap) return;
        pos.emplace_back(from, (int)list[from].size());
        list[from].push_back(Edge((int)list[to].size(), from, to, cap));
        list[to].push_back(Edge((int)list[from].size() - 1, to, from, 0));
    }
    
    // Dinic's algorithm
    COST dinic(COST limit_flow) {
        COST current_flow = 0;
        vector<int> level((int)list.size(), -1), iter((int)list.size(), 0);
        
        // Dinic BFS
        auto bfs = [&]() -> void {
            level.assign((int)list.size(), -1);
            level[S] = 0;
            queue<int> que;
            que.push(S);
            while (!que.empty()) {
                int v = que.front();
                que.pop();
                for (const Edge &e : list[v]) {
                    if (level[e.to] < 0 && e.cap > 0) {
                        level[e.to] = level[v] + 1;
                        if (e.to == T) return;
                        que.push(e.to);
                    }
                }
            }
        };
        
        // Dinic DFS
        auto dfs = [&](auto self, int v, COST up_flow) {
            if (v == T) return up_flow;
            COST res_flow = 0;
            for (int &i = iter[v]; i < (int)list[v].size(); ++i) {
                Edge &e = list[v][i], &re = get_rev_edge(e);
                if (level[v] >= level[e.to] || e.cap == 0) continue;
                COST flow = self(self, e.to, min(up_flow - res_flow, e.cap));
                if (flow <= 0) continue;
                res_flow += flow;
                e.cap -= flow, e.flow += flow;
                re.cap += flow, re.flow -= flow;
                if (res_flow == up_flow) break;
            }
            return res_flow;
        };
        
        // flow
        while (current_flow < limit_flow) {
            bfs();
            if (level[T] < 0) break;
            iter.assign((int)iter.size(), 0);
            while (current_flow < limit_flow) {
                COST flow = dfs(dfs, S, limit_flow - current_flow);
                if (!flow) break;
                current_flow += flow;
            }
        }
        return current_flow;
    };
    COST dinic() {
        return dinic(numeric_limits<COST>::max());
    }
};

int main() {
    int N, M;
    cin >> N >> M;
    vector<long long> A(N), B(M);
    for (int i = 0; i < N; ++i) cin >> A[i];
    for (int i = 0; i < M; ++i) cin >> B[i];
    vector<vector<int>> C(M);
    for (int i = 0; i < M; ++i) {
        int K;
        cin >> K;
        C[i].resize(K);
        for (int j = 0; j < K; ++j) {
            cin >> C[i][j];
            --C[i][j];
        }
    }
    
    // 家 i に入らない: F, 家 i に入る: T
    const long long INF = 1LL<<50;
    TwoVariableSubmodularOpt<long long> tvs(N+M, INF);
    for (int i = 0; i < N; ++i) {
        tvs.add_single_cost(i, 0, A[i]);
    }
    for (int j = 0; j < M; ++j) {
        tvs.add_single_cost(j+N, 0, -B[j]);
    }
    for (int j = 0; j < M; ++j) {
        for (auto c : C[j]) {
            tvs.add_psp_constraint(j+N, c);
        }
    }
    cout << -tvs.solve() << endl;
}