문제: icpc.me/11409
Maximum Cost Maximum Flow를 구하는 문제이다.
기존 MCMF 모델링에서 cost만 음수값으로 취해준 뒤 계산해주면 된다.
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 86 87 88 | #include <cstdio> #include <algorithm> #include <vector> #include <queue> #define INF 987654321 using namespace std; struct Edge { int v, cost, cap, rev; Edge(int v, int cost, int cap, int rev) : v(v), cost(cost), cap(cap), rev(rev){} }; int n, m; vector<vector<Edge>> vt; vector<int> pv, pe; void addEdge(int here, int there, int cost, int cap) { vt[here].emplace_back(there, cost, cap, vt[there].size()); vt[there].emplace_back(here, -cost, 0, vt[here].size() - 1); } bool spfa(int src, int sink) { vector<int> v(n + m + 2, 0); vector<int> dist(n + m + 2, INF); queue<int> qu; qu.push(src); dist[src] = 0; v[src] = 1; while (qu.size()) { int here = qu.front(); v[here] = 0; qu.pop(); for (int i = 0; i < vt[here].size();i++) { int there = vt[here][i].v; int cap = vt[here][i].cap; if (cap&&dist[there] > dist[here] + vt[here][i].cost) { dist[there] = dist[here] + vt[here][i].cost; pv[there] = here; pe[there] = i; if (!v[there]) { v[there] = 1; qu.push(there); } } } } return dist[sink] != INF; } pair<int, int> solve(int src, int sink) { int flow = 0, cost = 0; while (spfa(src, sink)) { int minFlow = INF; for (int i = sink; i != src; i = pv[i]) { int prev = pv[i]; int idx = pe[i]; minFlow = min(minFlow, vt[prev][idx].cap); } for (int i = sink; i != src; i = pv[i]) { int prev = pv[i]; int idx = pe[i]; vt[prev][idx].cap -= minFlow; vt[i][vt[prev][idx].rev].cap += minFlow; cost -= vt[prev][idx].cost*minFlow; } flow += minFlow; } return{ flow,cost }; } int main() { scanf("%d%d", &n, &m); vt.resize(n + m + 2); pv.assign(n + m + 2, -1); pe.assign(n + m + 2, -1); int src = n + m, sink = n + m + 1; for (int i = 0; i < n; i++) { int j; scanf("%d", &j); while (j--) { int a, b; scanf("%d%d", &a, &b); addEdge(i, a - 1 + n, -b, 1); } } for (int i = 0; i < n; i++) addEdge(src, i, 0, 1); for (int i = 0; i < m; i++) addEdge(i + n, sink, 0, 1); pair<int, int> res = solve(src, sink); printf("%d\n%d\n", res.first, res.second); return 0; } | cs |
'알고리즘 관련 > BOJ' 카테고리의 다른 글
BOJ)14428 수열과 쿼리 16 (0) | 2017.03.09 |
---|---|
BOJ)3640 제독 (0) | 2017.03.09 |
BOJ)11408 열혈강호5 (0) | 2017.03.09 |
BOJ)9370 미확인 도착지 (0) | 2017.03.08 |
BOJ)1252 이진수 덧셈 (0) | 2017.03.07 |