1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #include <queue> #define pii pair<int, int> #define MAXN (5000) #define MAXG (2500) #define MAXK (50) #define INF (0x7ffffff) #define rev(i) ((((i) - 1) ^ 1) + 1) #define dbh(i, j) (bh(i, j) + MAXG) #define bh(i, j) (((i) - 1) * MAXK + (j)) using namespace std; const int s = MAXN + 1, t = MAXN + 2; struct edg { int from, to, next, flow, cap, cost; edg() {} edg(int f, int nt, int n, int fl, int ca, int co): from(f), to(nt), next(n), flow(fl), cap(ca), cost(co) {} } b[MAXN * 100 + 5]; int pre[MAXN + 5], g[MAXN + 5], n, ans, kk, a[MAXN + 5], cntb; void ade(int fr, int nt, int ca, int co) { b[++cntb] = edg(fr, nt, g[fr], 0, ca, co); g[fr] = cntb; } bool spfa() { int dis[MAXN + 5], xa[MAXN + 5]; bool inq[MAXN + 5]; memset(xa, 0, sizeof(xa)); memset(inq, false, sizeof(inq)); for (int i = 0; i < MAXN + 5; i++) dis[i] = -INF; queue<int> q; q.push(s); dis[s] = 0; xa[s] = INF; while (!q.empty()) { int now = q.front(); q.pop(); inq[now] = false; for (int i = g[now]; i; i = b[i].next) if (b[i].cap > b[i].flow && dis[b[i].to] < dis[now] + b[i].cost) { xa[b[i].to] = min(b[i].cap - b[i].flow, xa[now]); dis[b[i].to] = dis[now] + b[i].cost; pre[b[i].to] = i; if (!inq[b[i].to]) q.push(b[i].to), inq[b[i].to] = true; } } return xa[t]; } void solve() { int x; while (x = spfa()) { for (int i = t; i != s; i = b[pre[i]].from) b[pre[i]].flow += x, b[rev(pre[i])].flow -= x, ans += b[pre[i]].cost * x; } } int main() { scanf("%d%d", &n, &kk); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { scanf("%d", &a[bh(i, j)]); ade(bh(i, j), dbh(i, j), 1, a[bh(i, j)]), ade(dbh(i, j), bh(i, j), 0, -a[bh(i, j)]); ade(bh(i, j), dbh(i, j), INF, 0), ade(dbh(i, j), bh(i, j), 0, 0); } for (int i = 1; i <= n; i++) for (int j = 1; j < n; j++) ade(dbh(i, j), bh(i, j + 1), INF, 0), ade(bh(i, j + 1), dbh(i, j), 0, 0); for (int i = 1; i < n; i++) for (int j = 1; j <= n; j++) ade(dbh(i, j), bh(i + 1, j), INF, 0), ade(bh(i + 1, j), dbh(i, j), 0, 0); ade(s, bh(1, 1), kk, 0), ade(bh(1, 1), s, 0, 0); ade(dbh(n, n), t, INF, 0), ade(t, dbh(n, n), 0, 0); solve(); printf("%d", ans); return 0; }
|