POJ 3422 Kaka's Matrix Travels(費用流),poj3422
POJ 3422 Kaka's Matrix Travels
題目連結
題意:一個矩陣,從左上方往右下角走k趟,每次走過數字就變成0,並且獲得這個數字,要求走完之後,所獲得數字之和最大
思路:有點類似區間k覆蓋的建圖方法,把點拆了,每個點有值的只能選一次,其他都是無值的,利用費用流,入點出點之間連一條容量1,有費用的邊,和一條容量k - 1,費用0的邊,然後其他就每個點和右邊和下邊2個點連邊,然後跑費用流
代碼:
#include <cstdio>#include <cstring>#include <vector>#include <queue>#include <algorithm>using namespace std;const int MAXNODE = 5005;const int MAXEDGE = 100005;typedef int Type;const Type INF = 0x3f3f3f3f;struct Edge {int u, v;Type cap, flow, cost;Edge() {}Edge(int u, int v, Type cap, Type flow, Type cost) {this->u = u;this->v = v;this->cap = cap;this->flow = flow;this->cost = cost;}};struct MCFC {int n, m, s, t;Edge edges[MAXEDGE];int first[MAXNODE];int next[MAXEDGE];int inq[MAXNODE];Type d[MAXNODE];int p[MAXNODE];Type a[MAXNODE];void init(int n) {this->n = n;memset(first, -1, sizeof(first));m = 0;}void add_Edge(int u, int v, Type cap, Type cost) {edges[m] = Edge(u, v, cap, 0, cost);next[m] = first[u];first[u] = m++;edges[m] = Edge(v, u, 0, 0, -cost);next[m] = first[v];first[v] = m++;}bool bellmanford(int s, int t, Type &flow, Type &cost) {for (int i = 0; i < n; i++) d[i] = INF;memset(inq, false, sizeof(inq));d[s] = 0; inq[s] = true; p[s] = s; a[s] = INF;queue<int> Q;Q.push(s);while (!Q.empty()) {int u = Q.front(); Q.pop();inq[u] = false;for (int i = first[u]; i != -1; i = next[i]) {Edge& e = edges[i];if (e.cap > e.flow && d[e.v] > d[u] + e.cost) {d[e.v] = d[u] + e.cost;p[e.v] = i;a[e.v] = min(a[u], e.cap - e.flow);if (!inq[e.v]) {Q.push(e.v); inq[e.v] = true;}}}}if (d[t] == INF) return false;flow += a[t];cost += d[t] * a[t];int u = t;while (u != s) {edges[p[u]].flow += a[t];edges[p[u]^1].flow -= a[t];u = edges[p[u]].u;}return true;}Type Mincost(int s, int t) {Type flow = 0, cost = 0;while (bellmanford(s, t, flow, cost));return cost;}} gao;const int N = 55;const int d[2][2] = {0, 1, 1, 0};int n, k, g[N][N];int main() {while (~scanf("%d%d", &n, &k)) {gao.init(n * n * 2);for (int i = 0; i < n; i++)for (int j = 0; j < n; j++) {scanf("%d", &g[i][j]);gao.add_Edge(i * n + j, i * n + j + n * n, k - 1, 0);gao.add_Edge(i * n + j, i * n + j + n * n, 1, -g[i][j]);}for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {for (int a = 0; a < 2; a++) {int x = i + d[a][0];int y = j + d[a][1];if (x < 0 || x >= n || y < 0 || y >= n) continue;int u = i * n + j, v = x * n + y;gao.add_Edge(u + n * n, v, k - 1, 0);}}}printf("%d\n", -gao.Mincost(0, n * n * 2 - 1));}return 0;}