hihocoder 1591 - 錦標賽(費用流)
阿新 • • 發佈:2018-11-22
思路:拆點,每個點拆成兩個,限流的不用多說了吧。然後,關鍵在於某點A和B有邊,但是實際結果只能二選一,怎麼辦呢?弄一個輔助點C加邊方式(A’,C,1,-SC[A][B]), (B',C,1,-SC[B][A]), (C,C', 1, 0), (C',T, INF, 0); //(U,V,CAP,COST)
程式碼:
#include <stdio.h> #include <string.h> #include <vector> #include <string> #include <cmath> #include <ctime> #include <queue> #include <stack> #include <set> #include <iostream> #include <map> #include <algorithm> const double PI = acos(-1.0); const double EPS = 1e-9; using namespace std; const int MAXN = 50000; const int MAXM = 500000; const int INF = 0x3f3f3f3f; struct Edge { int to, next, cap, flow, cost; }edge[MAXM]; int head[MAXN], tol; int pre[MAXN], dis[MAXN]; bool vis[MAXN]; int N;//節點總個數,節點編號從0~N-1 void init() { tol = 0; memset(head, -1, sizeof(head)); } void addedge(int u, int v, int cap, int cost) { edge[tol].to = v; edge[tol].cap = cap; edge[tol].cost = cost; edge[tol].flow = 0; edge[tol].next = head[u]; head[u] = tol++; edge[tol].to = u; edge[tol].cap = 0; edge[tol].cost = -cost; edge[tol].flow = 0; edge[tol].next = head[v]; head[v] = tol++; } bool spfa(int s, int t) { queue<int>q; for (int i = 0; i < N; i++) { dis[i] = INF; vis[i] = false; pre[i] = -1; } dis[s] = 0; vis[s] = true; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); vis[u] = false; for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; if (edge[i].cap > edge[i].flow && dis[v] > dis[u] + edge[i].cost) { dis[v] = dis[u] + edge[i].cost; pre[v] = i; if (!vis[v]) { vis[v] = true; q.push(v); } } } } if (pre[t] == -1)return false; else return true; } //返回的是最大流,cost存的是最小費用 int minCostMaxflow(int s, int t, int &cost) { int flow = 0; cost = 0; while (spfa(s, t)) { int Min = INF; for (int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to]) { if (Min > edge[i].cap - edge[i].flow) Min = edge[i].cap - edge[i].flow; } for (int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to]) { edge[i].flow += Min; edge[i ^ 1].flow -= Min; cost += edge[i].cost * Min; } flow += Min; } return flow; } bool flag[105][105]; int sc[105][105]; int n, st, ed; void add(int i, int j) { addedge(i+n, N, 1, -sc[i][j]); addedge(j+n, N, 1, -sc[j][i]); N++; addedge(N - 1, N, 1, 0); addedge(N, ed, INF, 0); N++; } int main() { int a[105]; while (scanf("%d", &n) != EOF) { ed = 2 * n + 1; N = 2 * n + 2; memset(flag, 0, sizeof(flag)); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); int m; scanf("%d", &m); for (int i = 1; i <= m; i++) { int x, y; scanf("%d%d", &x, &y); a[x]--; flag[x][y] = true; } int sum = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { scanf("%d", &sc[i][j]); if (flag[i][j]) { sum += sc[i][j]; sc[i][j] = -1; } if (flag[j][i]) sc[i][j] = -1; } } init(); for (int i = 1; i <= n; i++) { addedge(st, i, INF, 0); addedge(i, i + n, a[i], 0); for (int j = i+1; j <= n; j++) { if (sc[i][j] != -1) { add(i, j); } } } int ans = 0; minCostMaxflow(st, ed, ans); cout << sum-ans << endl; } return 0; }