POJ 3422 Kaka's Matrix Travels 费用流(用过后变成0的处理)

来源:互联网 发布:电脑怎么用手机网络 编辑:程序博客网 时间:2024/05/16 08:01
题目大意:给出一个网格,每次的起点都是左上角,且只能往下或者往右走,终点是右下角,每走过一个格子,可以将该格子内的数拿走,格子内的数只能被拿走一次 

问,走k次,拿到的数的总和的最大值是多少


需要注意的两点

第一点:费用流或者网络流求最大值的时候,存在是相反数,求最小值。

第二点:对于”格子内的数只能被拿走一次 "也就是用完之后不能重复利用的这种,不能让边权等于目标点的值这样建图。而是拆点。(i,i’,1,val[i])和(i',j,1,0)。 经过是获得值,回去是只能得到0.


#include <cstdio>#include <cstring>#include <queue>#include <vector>#include <algorithm>usingnamespacestd;constint MAXNODE = 10010;constint MAXEDGE = 1000010;typedefint Type;const Type INF = 0x3f3f3f3f;struct Edge{ int u, v, next; Type cap, flow, cost; Edge() {} Edge(int u, int v, Type cap, Type flow, Type cost, int next): u(u), v(v), cap(cap), flow(flow), cost(cost), next(next) {}};struct MCMF{ int n, m, s, t; Edge edges[MAXEDGE]; int head[MAXNODE]; int p[MAXNODE]; Type d[MAXNODE]; Type a[MAXNODE]; bool inq[MAXNODE]; void init(int n) { this->n = n; memset(head, -1,sizeof(head)); m = 0; } void AddEdge(int u, int v, Type cap, Type cost) { edges[m] = Edge(u, v, cap, 0, cost, head[u]); head[u] = m++; edges[m] = Edge(v, u, 0,0, -cost, head[v]); head[v] = m++; } bool BellmanFord(int s, int t, Type &flow, Type &cost) { for (int i = 0; i < n; i++) d[i] = INF; memset(inq,0,sizeof(inq)); d[s] = 0; inq[s] = true; p[s] = 0; a[s] = INF; queue<int> Q; Q.push(s); while (!Q.empty()) { int u = Q.front(); Q.pop(); inq[u] = false;for (int i = head[u]; ~i; i = edges[i].next) { 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) returnfalse; flow += a[t]; cost += a[t] * d[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; } returntrue; } Type MinCost(int s, int t, int k) { this->s = s; this->t = t; Type flow = 0, cost = 0;while (BellmanFord(s, t, flow, cost)){// printf("flow is %d\n", flow);if (flow == k) break; } return cost; }}mcmf;#define maxn 60int n, k;int num[maxn][maxn];int dir[2][2] = {{0, -1}, {-1,0}};void init() { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) scanf("%d", &num[i][j]);}void solve() { int t = n * n; mcmf.init(t * 2 + 3);for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { mcmf.AddEdge((i - 1) * n + j, (i - 1) * n + j + t, 1, -num[i][j]); mcmf.AddEdge((i - 1) * n + j, (i - 1) * n + j + t, k, 0); } for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) for (int l = 0; l < 2; l++) { int tx = i + dir[l][0];int ty = j + dir[l][1];if (tx < 1 || tx > n || ty < 1 || ty > n) continue; mcmf.AddEdge((tx - 1) * n + ty + t, (i - 1) * n + j, k, 0); } mcmf.AddEdge(t * 2 + 1,1, k, 0); mcmf.AddEdge(t * 2, t * 2 + 2, k, 0);printf("%d\n", -mcmf.MinCost(t * 2 + 1, t * 2 + 2, k));}int main() { while (scanf("%d%d", &n, &k) != EOF) { init(); solve(); } return0;}