Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define rep(i, a, b) for(int i = a; i < (b); ++i)
- #define all(x) begin(x), end(x)
- #define sz(x) (int)(x).size()
- typedef long long ll;
- typedef pair<int, int> pii;
- typedef vector<int> vi;
- const ll INF = numeric_limits<ll>::max() / 4;
- struct MCMF {
- struct edge {
- int from, to, rev;
- ll cap, cost, flow;
- };
- int N;
- vector<vector<edge>> ed;
- vector<ll> dist, pi;
- vector<edge*> par;
- MCMF(int N) : N(N), ed(N), dist(N), pi(N), par(N) {}
- void addEdge(int from, int to, ll cap, ll cost) {
- if (from == to) return;
- ed[from].push_back(edge{ from,to,sz(ed[to]),cap,cost,0 });
- ed[to].push_back(edge{ to,from,sz(ed[from])-1,0,-cost,0 });
- }
- void path(int s) {
- fill(all(dist), INF);
- dist[s] = 0;
- priority_queue<pair<ll, int>> q;
- q.push({ 0, s });
- while (!q.empty()) {
- auto [d,u] = q.top(); q.pop();
- if (-d > dist[u]) continue;
- for (edge& e : ed[u]) {
- ll val = pi[u] - d - pi[e.to] + e.cost;
- if (e.cap - e.flow > 0 && val < dist[e.to]) {
- dist[e.to] = val;
- par[e.to] = &e;
- q.push({ -dist[e.to], e.to });
- }
- }
- }
- rep(i,0,N) pi[i] = min(pi[i] + dist[i], INF);
- }
- pair<ll, ll> maxflow(int s, int t) {
- ll totflow = 0, totcost = 0;
- while (path(s), dist[t]!=INF) {
- ll fl = INF;
- for (edge* x = par[t]; x; x = par[x->from])
- fl = min(fl, x->cap - x->flow);
- totflow += fl;
- for (edge* x = par[t]; x; x = par[x->from]) {
- x->flow += fl;
- ed[x->to][x->rev].flow -= fl;
- }
- }
- rep(i,0,N) for(edge& e : ed[i]) totcost += e.cost * e.flow;
- return {totflow, totcost/2};
- }
- // If some costs can be negative, call this before maxflow:
- void setpi(int s) { // (otherwise, leave this out)
- fill(all(pi), INF); pi[s] = 0;
- int it = N, ch = 1; ll v;
- while (ch-- && it--)
- rep(i,0,N) if (pi[i] != INF)
- for (edge& e : ed[i]) if (e.cap)
- if ((v = pi[i] + e.cost) < pi[e.to])
- pi[e.to] = v, ch = 1;
- assert(it >= 0); // negative cost cycle
- }
- };
- int main() {
- cin.tie(0)->sync_with_stdio(0);
- int sat[3][4] = {
- {4,3,2,1},
- {8,7,6,5},
- {12,11,10,9}
- };
- int n, m;
- while (cin >> n >> m && n) {
- int numnodes = n + m + 2;
- MCMF flow(numnodes);
- int source = numnodes - 1;
- int sink = numnodes - 2;
- rep(i, 0, n) {
- int c;
- cin >> c;
- flow.addEdge(m + i, sink, c, 0);
- }
- rep(i, 0, m) {
- flow.addEdge(source, i, 1, 0);
- }
- rep(i, 0, m) {
- int y,c1,c2,c3,c4;
- cin >> y >> c1 >> c2 >> c3 >> c4;
- y--;
- int choice[4] = { c1,c2,c3,c4 };
- rep(j, 0, 4) {
- flow.addEdge(i, m + choice[j], 1, -sat[y][j]);
- }
- }
- flow.setpi(source);
- cout << -flow.maxflow(source, sink).second << "\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment