1 #include<bits/stdc++.h> 2 using namespace std; 3 #define INF 0x3f3f3f3f 4 #define M(a, b) memset(a, b, sizeof(a)) 5 const int N = 1e3 + 5; 6 struct Edge { 7 int from, to, cap, flow, cost; 8 }; 9 10 struct MCMF { 11 int n, m; 12 vector<Edge> edges; 13 vector<int> G[N]; 14 int d[N], inq[N], p[N], a[N]; 15 16 void init(int n) { 17 this->n = n; 18 for (int i = 0; i < n; ++i) G[i].clear(); 19 edges.clear(); 20 } 21 22 void AddEdge(int from, int to, int cap, int cost) { 23 edges.push_back((Edge){from, to, cap, 0, cost}); 24 edges.push_back((Edge){to, from, 0, 0, -cost}); 25 m = edges.size(); 26 G[from].push_back(m-2); G[to].push_back(m-1); 27 } 28 29 bool spfa(int s, int t, int &flow, int &cost) { 30 M(inq, 0); M(d, INF); 31 d[s] = 0; inq[s] = 1; 32 queue<int> q; 33 q.push(s); 34 while (!q.empty()) { 35 int x = q.front(); q.pop(); 36 inq[x] = 0; 37 for (int i = 0; i < G[x].size(); ++i) { 38 Edge &e = edges[G[x][i]]; 39 if (d[e.to] > d[x] + e.cost && e.cap > e.flow) { 40 d[e.to] = d[x] + e.cost; 41 p[e.to] = G[x][i]; 42 a[e.to] = min(a[x], e.cap-e.flow); 43 if (inq[e.to]) continue; 44 q.push(e.to); inq[e.to] = 1; 45 } 46 } 47 } 48 if (d[t] == INF) return false; 49 flow += a[t]; 50 cost += d[t] * a[t]; 51 int u = t; 52 while (u != s) { 53 edges[p[u]].flow += a[t]; 54 edges[p[u]^1].flow -= a[t]; 55 u = edges[p[u]].from; 56 } 57 return true; 58 } 59 60 int Mincost(int s, int t) { 61 int flow = 0, cost = 0; 62 while (spfa(s, t, flow, cost)); 63 return cost; 64 } 65 66 };
时间: 2024-10-24 20:04:56