Description
求两次从左上角走向右下角并获取点权的最大收益
Solution
第一眼四维dp,然后否定了
考虑费用流。我们拆点限制走过一个点的次数,起点和终点多连一条流量为1费用为0的边保证能走两次。然后就A了
Code
#include <stdio.h>
#include <string.h>
#include <queue>
#define rep(i, st, ed) for (int i = st; i <= ed; i += 1)
#define erg(i, st) for (int i = ls[st]; i; i = e[i].next)
#define fill(x, t) memset(x, t, sizeof(x))
#define INF 0x3f3f3f3f
#define L 1201
#define N L * L
#define E N * 20 + 1
struct edge{int x, y, w, c, next;}e[E];
int ls[N];
inline void addEdge(int &cnt, int x, int y, int w, int c){
cnt += 1; e[cnt] = (edge){x, y, w, c, ls[x]}; ls[x] = cnt;
cnt += 1; e[cnt] = (edge){y, x, 0, -c, ls[y]}; ls[y] = cnt;
}
using std:: queue;
int inQueue[N], dis[N], pre[N];
inline int spfa(int st, int ed){
queue<int> que;
que.push(st);
fill(inQueue, 0);
inQueue[st] = 1;
fill(dis, -31);
int inf = dis[st];
dis[st] = 0;
while (!que.empty()){
int now = que.front(); que.pop();
erg(i, now){
if (e[i].w > 0 && dis[now] + e[i].c > dis[e[i].y]){
dis[e[i].y] = dis[now] + e[i].c;
pre[e[i].y] = i;
if (!inQueue[e[i].y]){
inQueue[e[i].y] = 1;
que.push(e[i].y);
}
}
}
inQueue[now] = 0;
}
return dis[ed] != inf;
}
inline int min(int x, int y){
return x<y?x:y;
}
inline int modify(int ed){
int ret = 0, mn = INF;
for (int i = ed; pre[i]; i = e[pre[i]].x){
ret += e[pre[i]].c;
mn = min(e[pre[i]].w, mn);
}
for (int i = ed; pre[i]; i = e[pre[i]].x){
e[pre[i]].w -= mn;
e[pre[i] ^ 1].w += mn;
}
return ret * mn;
}
inline int mcf(int st, int ed){
int tot = 0;
while (spfa(st, ed)){
tot += modify(ed);
}
return tot;
}
int num[L][L], rc[L][L];
int main(void){
int n;
while (~scanf("%d", &n)){
rep(i, 1, n){
rep(j, 1, n){
scanf("%d", &rc[i][j]);
num[i][j] = (i - 1) * n + j;
}
}
int edgeCnt = 1;
int lim = n * n;
fill(ls, 0);
rep(i, 1, n){
rep(j, 1, n){
if (i < n){
addEdge(edgeCnt, num[i][j] + lim, num[i + 1][j], INF, 0);
}
if (j < n){
addEdge(edgeCnt, num[i][j] + lim, num[i][j + 1], INF, 0);
}
addEdge(edgeCnt, num[i][j], num[i][j] + lim, 1, rc[i][j]);
}
}
addEdge(edgeCnt, num[1][1], num[1][1] + lim, 1, 0);
addEdge(edgeCnt, num[n][n], num[n][n] + lim, 1, 0);
int ans = mcf(1, lim + lim);
printf("%d\n", ans);
}
return 0;
}