题意
从左上角到右下角走 每个格子都有一个点权 每次经过都可以拿走但只能拿一次 问走k次所拿走的点权和最大为多少
思路
dp行不通 因为k太大了 如果是两次的话可以用f[k, x1, x2]来进行dp
用最大费用流 每个格子向右向下连边 容量为INF 因为可以多次走
由于点权问题 所以拆点 边权为点权
重点来了:
因为每个格子的值只能拿一次 但是如果通俗建边是无法保证只拿一次的
所以我们可以建两条边 一条为容量为1 费用为点权的边以及一条容量为INF 但是费用为0的边 则保证了最多只拿一次这个格子的值
跑一遍最大费用流则可得到答案
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 5010, M = 20010, INF = 1e8;
int n, k, S, T;
int h[N], e[M], ne[M], f[M], w[M], idx;
int d[N], pre[N], incf[N];
bool st[N];
queue<int> q;
int get(int i, int j , int t)
{
return (i * n + j) * 2 + t;
}
void add(int a, int b, int c, int d)
{
e[idx] = b, ne[idx] = h[a], f[idx] = c, w[idx] = d, h[a] = idx ++ ;
e[idx] = a, ne[idx] = h[b], f[idx] = 0, w[idx] = -d, h[b] = idx ++ ;
}
bool spfa()
{
memset(d, -0x3f, sizeof d);
memset(incf, 0, sizeof incf);
q.push(S), d[S] = 0, incf[S] = INF;
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int ver = e[i];
if (f[i] && d[ver] < d[t] + w[i])
{
d[ver] = d[t] + w[i];
incf[ver] = min(f[i], incf[t]);
pre[ver] = i;
if (!st[ver])
{
st[ver] = true;
q.push(ver);
}
}
}
}
return incf[T] > 0;
}
int EK()
{
int cost = 0;
while (spfa())
{
int t = incf[T];
cost += t * d[T];
for (int i = T; i != S; i = e[pre[i] ^ 1])
{
f[pre[i]] -= t;
f[pre[i] ^ 1] += t;
}
}
return cost;
}
int main()
{
scanf("%d%d", &n, &k);
S = n * n * 2, T = S + 1;
memset(h, -1, sizeof h);
add(S, get(0, 0, 0), k, 0);
add(get(n - 1, n - 1, 1), T, k, 0);
for (int i = 0; i < n; i ++ )
for (int j = 0; j < n; j ++ )
{
int c;
scanf("%d", &c);
add(get(i, j, 0), get(i, j, 1), 1, c);
add(get(i, j, 0), get(i, j, 1), INF, 0);
if (i + 1 < n) add(get(i, j, 1), get(i + 1, j, 0), INF, 0);
if (j + 1 < n) add(get(i, j, 1), get(i, j + 1, 0), INF, 0);
}
printf("%d\n", EK());
return 0;
}