Composition Method:
Note that the side in the question is undirected. The New Source Vertex S and sink vertex t are connected to one side with a capacity of 1 and a cost of W. S to 1 connects to a side with a capacity of 1 and the cost is 0. n to T connects to a side with a capacity of 1 and the cost is 0, and calculates the maximum flow.
# Include <iostream> # include <cstring> # include <cstdlib> # include <cstdio> # include <algorithm> # include <queue> # include <vector> # include <cmath> # define ll long longusing namespace STD; const int maxn = 10000 + 10; const int INF = 1000000000; struct edge {int from, to, Cap, flow, cost; edge (int u, int V, int C, int F, int W): From (u), to (v), Cap (C), flow (F), Cost (w) {}}; int n, m; vector <edge> edges; vector <int> G [maxn]; Int INQ [maxn]; int d [maxn]; int P [maxn]; int A [maxn]; void Init () {for (INT I = 0; I <= n + 1; I ++) g [I]. clear (); edges. clear ();} void addedge (int from, int to, int cap, int cost) {edges. push_back (edge (from, to, Cap, 0, cost); edges. push_back (edge (to, from, 0, 0,-cost); int M = edges. size (); G [from]. push_back (M-2); G [to]. push_back (M-1);} bool spfa (int s, int T, Int & flow, ll & cost) {for (INT I = 0; I <= n + 1; I ++) d [I] = inf; MEMS Et (INQ, 0, sizeof (INQ); D [s] = 0; INQ [s] = 1; p [s] = 0; A [s] = inf; queue <int> q; q. push (s); While (! Q. empty () {int u = Q. front (); q. pop (); INQ [u] = 0; For (INT I = 0; I <G [u]. size (); I ++) {edge & E = edges [G [u] [I]; If (E. cap> E. flow & D [E. to]> d [u] + E. cost) {d [E. to] = d [u] + E. cost; P [E. to] = G [u] [I]; A [E. to] = min (A [u], E. cap-e.flow); If (! INQ [E. to]) {q. push (E. to); INQ [E. to] = 1 ;}}}if (d [T] = inf) return false; flow + = A [T]; Cost + = (LL) d [T] * (LL) A [T]; for (INT u = T; u! = S; u = edges [p [u]. from) {edges [p [u]. flow + = A [T]; edges [p [u] ^ 1]. flow-= A [T];} return true;} int mincostmaxflow (int s, int T, ll & cost) {int flow = 0; cost = 0; while (spfa (S, T, flow, cost); return flow;} int main () {While (scanf ("% d", & N, & M )! = EOF) {Init (); int U, V, W; For (INT I = 1; I <= m; I ++) {scanf ("% d", & U, & V, & W); addedge (u, v, 1, W); addedge (v, U, 1, W);} int S = 0, T = n + 1; addedge (s, 1, 2, 0); addedge (n, T, 2, 0); ll cost = 0; int ans = mincostmaxflow (S, T, cost); printf ("% LLD \ n", cost);} return 0 ;}