Split each point into the origin A and pseudo point b,a->b there are two one-way (adjacency table implementation needs to establish a reverse empty edge, and to ensure that the loop cost and 0), a residual capacity of 1, the cost of its own negative value (easy to calculate the shortest path), the other residual capacity +∞, the cost is 0 ( The point is guaranteed to pass multiple times, but only once for the cost.
In addition, the pseudo point B and the right side of the origin and the point below a one-way road (adjacency table implementation needs to establish a reverse empty edge), the residual capacity of +∞, the cost is 0. Source point 0 to 1 there is a one-way road, residual capacity is K (can pass K), the last point of the pseudo-point 2*n*n and Sink point 2*n*n+1 have a one-way edge, the residual capacity of K, two side of the cost is 0.
Once the composition is successful, go to the minimum cost maximum flow.
Minimum cost max flow problem-split//time:47ms memory:624k#include<iostream> #include <cstring> #include <cstdio># Include<algorithm> #include <queue>using namespace std; #define MAX 55#define MAXN 5005#define INF 0x3f3f3f3fstruct edge{int u,v,r,w,next; Edge () {} edge (int u,int v,int r,int w,int N): U (U), V (v), R (R), W (W), Next (N) {}}e[maxn*8];int n,k;int s,t;int h[maxn],le;int M[max][max];int pre[maxn];int cost[maxn];bool vis[maxn];void Add (int u,int v,int r,int w) {E[le] = Edge (U,v,r,w,h[u]); H[u] = le++; E[le] = Edge (V,u,0,-w,h[v]); H[V] = le++;} void Build () {Add (S, 1, K, 0); Add (2*n*n, T, K, 0); for (int i = 1; I <= n*n; i++) {Add (I, N*n+i, 1,-m[(i-1)/n + 1][(i-1)%n + 1]); Add (i, n*n+i, K, 0); if (i% n) Add (I+n*n, i+1, INF, 0); if (I <= n (n-1)) Add (I+n*n, I+n, INF, 0); }}bool SPFA () {memset (pre,-1,sizeof (pre)); memset (vis,false,sizeof (VIS)); memset (cost,inf,sizeof (cost)); Queue<int> Q; Q.push (s); Cost[s] = 0; Vis[s] = true; while (!q.empty ()) {int cur = q.front (); Q.pop (); Vis[cur] = false; for (int i = h[cur]; i =-1; i = e[i].next) {int v = E[I].V; if (E[I].R && cost[v] > Cost[cur] + e[i].w) {Cost[v] = Cost[cur] + e[i].w; PRE[V] = i; if (!vis[v]) {Vis[v] = true; Q.push (v); }}}} return cost[t] = = INF? False:true;} int Maxcostflow () {int maxflow = 0; while (SPFA ()) {//augmented road int mind = INF; for (int i = pre[t]; I! =-1; i = pre[e[i].u]) mind = min (mind, E[I].R); for (int i = pre[t]; I! =-1; i = pre[e[i].u]) {E[I].R-= mind; E[I^1].R + = mind; } Maxflow + = Mind*cost[t]; } return maxflow;} int main () {//freopen ("In.txt", "R", stdin); memset (H,-1, sizeof (h)); scanf ("%d%d", &n,&k); s = 0; t = 2*n*n+1; for (int i = 1; I <= n; i++) for (int j = 1; J <= N; j + +) scanf ("%d", &m[i][j]); Build (); printf ("%d\n",-maxcostflow ()); return 0;}
ACM/ICPC Card matrix Travel-Minimum cost maximum flow (template available) (POJ3422)