题意:N*N的地图上每格都有分数,分数只能获取一次。有人从左上方开始,每次向右或下移动一格,到右下方为止,记为一次环游。问第K次环游后累计分数的最大值?
第一次做最小费用流,参考别人的做法,思考了好久,还是有点不太明白,还是网络流的题目做的太少,不太熟,还得多做几个加深理解才行。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
typedef pair<int, int> P; ///first保存最短距离,second保存定点编号
const int maxn = 50*50*2 + 7;
const int INF = 0x3f3f3f3f;
int n, k, V;
int h[maxn], dis[maxn], pa_v[maxn], pa_e[maxn];
/// 顶点的势, 最短距离, 父亲节点, 父亲节点的边
struct edge{
int to, cap, cost, rev;///终点, 容量, 费用, 反向边
edge(int to, int cap, int cost, int rev) : to(to), cap(cap), cost(cost), rev(rev) {}
};
vector<edge> G[maxn];
void add_edge(int from, int to, int cap, int cost) {
G[from].push_back(edge(to, cap, cost, G[to].size()));
G[to].push_back(edge(from, 0, -cost, G[from].size()-1));
}
int min_cost_flow(int s, int t, int f) {
int res = 0;
memset(h, 0, sizeof(h));
while(f > 0) {
priority_queue<P, vector<P>, greater<P> > que;
memset(dis, INF, sizeof(dis));
dis[s] = 0;
que.push(P(0, s));
while(!que.empty()) {
P p = que.top(); que.pop();
int v = p.second;
if(dis[v] < p.first) continue;
for(int i = 0; i < G[v].size(); ++i) {
edge &e = G[v][i];
if(e.cap > 0 && dis[e.to] > dis[v] + e.cost + h[v] - h[e.to]) {
dis[e.to] = dis[v] + e.cost + h[v] - h[e.to];
pa_v[e.to] = v;
pa_e[e.to] = i;
que.push(P(dis[e.to], e.to));
}
}
}
if(dis[t] == INF) return -1;
for(int v = 0; v < V; ++v) {
h[v] += dis[v];
}
int d = f;
for(int v = t; v != s; v = pa_v[v]) {
d = min(d, G[pa_v[v]][pa_e[v]].cap);
}
f -= d;
res += d*h[t];
for(int v = t; v != s; v = pa_v[v]) {
edge &e = G[pa_v[v]][pa_e[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
int main() {
while(~scanf("%d%d", &n, &k)) {
V = 2*n*n+1;
add_edge(0, 1, k, 0);
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
int t; scanf("%d", &t);
int num = (i*n+j)*2+1;
add_edge(num, num+1, 1, -t);
add_edge(num, num+1, k, 0);
if(i+1<n) {
int down = ((i+1)*n+j)*2+1;
add_edge(num+1, down, k, 0);
}
if(j+1<n) {
int right = (i*n+j+1)*2+1;
add_edge(num+1, right, k, 0);
}
}
}
printf("%d\n", -min_cost_flow(0, V-1, k));
}
}