# Lugu2045 grid access enhanced version

### Title Description

Given a matrix of n*n, each lattice has a non negative integer AIJ, (AIJ < = 1000). Now, starting from (1,1), you can go right or down, and finally arrive at (n,n). Every time you reach a lattice, take out the number of the lattice, the number of the lattice will become 0, so you can go K times in total, and now you need the maximum sum of the number of squares reached by K times

### Input format:

Two numbers in the first row n,k (1 < = n < = 50, 0 < = k < = 10)
Next N lines, n numbers per line, respectively represent the number of each lattice of the matrix

### Output format:

A number, which is the maximum sum

```3 1
1 2 3
0 2 1
1 4 2
```

```11
```

### Explain

No more than 1000 per cell

Split each point into two
An edge with a connection capacity of INF and a charge of 0
An edge with a connection capacity of 1 and a cost of the opposite weight
Then run the minimum cost and the maximum flow k times
Just make the array bigger

```# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
# define Copy(a, b) memcpy(a, b, sizeof(a))
# define ID(a, b) n * (a - 1) + b
using namespace std;
typedef long long ll;
const int _(5010), __(1e7 + 10), INF(2147483647);

RG char c = getchar(); RG ll x = 0, z = 1;
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}

int n, k, fst[_], nxt[__], to[__], cnt, w[__], cost[__];
int S, T, max_flow, max_cost, dis[_], pv[_], pe[_], vis[_];
queue <int> Q;

IL void Add(RG int u, RG int v, RG int f, RG int co){
cost[cnt] = co; w[cnt] = f; to[cnt] = v; nxt[cnt] = fst[u]; fst[u] = cnt++;
cost[cnt] = -co; w[cnt] = 0; to[cnt] = u; nxt[cnt] = fst[v]; fst[v] = cnt++;
}

IL bool Bfs(){
Fill(dis, 127); dis[S] = 0; vis[S] = 1; Q.push(S);
while(!Q.empty()){
RG int u = Q.front(); Q.pop();
for(RG int e = fst[u]; e != -1; e = nxt[e])
if(w[e] && dis[to[e]] > dis[u] + cost[e]){
dis[to[e]] = dis[u] + cost[e];
pe[to[e]] = e; pv[to[e]] = u;
if(!vis[to[e]]) vis[to[e]] = 1, Q.push(to[e]);
}
vis[u] = 0;
}
if(dis[T] >= dis[T + 1]) return 0;
RG int ret = INF;
for(RG int u = T; u != S; u = pv[u]) ret = min(ret, w[pe[u]]);
max_cost -= ret * dis[T]; max_flow += ret;
for(RG int u = T; u != S; u = pv[u]) w[pe[u]] -= ret, w[pe[u] ^ 1] += ret;
return 1;
}

int main(RG int argc, RG char* argv[]){
S = 1; T = 2 * n * n;
for(RG int i = 1; i <= n; ++i)
for(RG int j = 1, a; j <= n; ++j){
a = Read(); RG int t = ID(i, j);
Add(t, t + n * n, 1, -a); Add(t, t + n * n, INF, 0);
if(i < n) Add(t + n * n, ID(i + 1, j), INF, 0);
if(j < n) Add(t + n * n, ID(i, j + 1), INF, 0);
}
while(k--) Bfs();
printf("%d\n", max_cost);
return 0;
}
```

Posted on Sun, 03 May 2020 03:31:50 -0400 by Axem