Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 2686
Same as poj3422
Delete K and change the size of the sink point and source point to 2 (because there are two options ).
# Include <iostream> # include <cstdlib> # include <cstdio> # include <cstring> # include <queue> # include <algorithm> const int maxn = 20000; const int maxm = 800000; const int INF = 1e8; const int INF = 0x3f3f3f; # define min int_min # define Max 1e6 # define ll long # define Init () memset (A, 0, sizeof (A) # define for (I, a, B) for (INT I = A; I <B; I ++) # define max (A, B) (A> B )? (A) :( B) # define min (A, B) (A> B )? (B) :( A) using namespace STD; struct node {int U, V, W, Cap, next;} edge [maxm]; int pre [maxn], dis [maxn], head [maxn], CNT; bool vis [maxn]; int N; void add (int u, int V, int C, int cap) {edge [CNT]. U = u; edge [CNT]. V = V; edge [CNT]. W = C; edge [CNT]. CAP = CAP; edge [CNT]. next = head [u]; head [u] = CNT ++; edge [CNT]. U = V; edge [CNT]. V = u; edge [CNT]. W =-C; edge [CNT]. CAP = 0; edge [CNT]. next = head [v]; head [v] = CNT ++;} int spfa (int s, int t) {queu E <int> q; while (Q. empty () = false) Q. pop (); q. push (s); memset (VIS, 0, sizeof (VIS); memset (PRE,-1, sizeof (pre); for (I, s, t + 1) dis [I] =-1; // obtain the longest path dis array and initialize it to-1 dis [s] = 0; vis [s] = 1; while (! Q. empty () {int u = Q. front (); q. pop (); vis [u] = 0; For (INT I = head [u]; I! =-1; I = edge [I]. next) {If (edge [I]. cap & dis [edge [I]. v] <(DIS [u] + edge [I]. w) // obtain the longest path {dis [edge [I]. v] = dis [u] + edge [I]. w; Pre [edge [I]. v] = I; If (! Vis [edge [I]. v]) {vis [edge [I]. v] = 1; q. push (edge [I]. v) ;}}} if (DIS [T]! =-1) // ------------------ forgot to change .. Return 1; else return 0;} int mincostmaxflow (int s, int t) {int flow = 0, cost = 0; while (spfa (S, T )) {int df = inf; For (INT I = pre [T]; I! =-1; I = pre [edge [I]. u]) {If (edge [I]. cap <DF) df = edge [I]. CAP;} flow + = DF; For (INT I = pre [T]; I! =-1; I = pre [edge [I]. u]) {edge [I]. cap-= DF; edge [I ^ 1]. cap + = DF;} // printf ("df = % d \ n", DF); Cost + = dis [T] * DF;} return cost ;} void initt () {CNT = 0; memset (Head,-1, sizeof (head) ;}int Ma; int main () {int S, T, K; while (~ Scanf ("% d", & N) {initt (); s = 0; t = 2 * n + 1; add (s, 1, 0, 2 ); int num = N * n; for (I, 1, n + 1) {for (J, 1, n + 1) {scanf ("% d", & Ma ); add (I-1) * n + J, (I-1) * n + J + num, Ma, 1); add (I-1) * n + J, (I-1) * n + J + num,); // This point is connected to the split point. The fee is 0 and the capacity is infinite if (I <= N-1) // downward graph {Add (I-1) * n + J + num, I * n + J,);} If (j <= N-1) // right build graph {Add (I-1) * n + J + num, (I-1) * n + J +, 1) ;}} add (t-1, T, 0, 2); int ans = mincostmaxflow (S, T); printf ("% d \ n", ANS);} return 0 ;}