Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- ifstream fin("fmcm.in");
- ofstream fout("fmcm.out");
- int N, source, sink;
- bool flag;
- vector < vector < int > > Graph, Capacity, Cost;
- vector < int > parent, D;
- const int INF = 2e9;
- inline void min_self(int& a, int b) {
- a = min(a, b);
- }
- int SPFA() {
- D.assign(N + 1, INF);
- parent.assign(N + 1, -1);
- D[source] = 0;
- queue < int > Q;
- Q.emplace(source);
- vector < bool > inQ(N + 1);
- inQ[source] = true;
- while(!Q.empty()) {
- int curr = Q.front();
- Q.pop();
- inQ[curr] = false;
- for(int next : Graph[curr])
- if(Capacity[curr][next] && D[curr] + Cost[curr][next] < D[next]) {
- D[next] = D[curr] + Cost[curr][next];
- parent[next] = curr;
- if(!inQ[next]) {
- Q.emplace(next);
- inQ[next] = true;
- }
- }
- }
- if(D[sink] != INF) {
- flag = true;
- int new_flow = INF;
- for(int node = sink; node != source; node = parent[node])
- min_self(new_flow, Capacity[parent[node]][node]);
- if(new_flow == 0)
- return 0;
- for(int node = sink; node != source; node = parent[node]) {
- Capacity[parent[node]][node] -= new_flow;
- Capacity[node][parent[node]] += new_flow;
- }
- return new_flow * D[sink];
- }
- return 0;
- }
- int min_cost_flow() {
- int ans = 0;
- flag = true;
- while(flag) {
- flag = false;
- ans += SPFA();
- }
- return ans;
- }
- int main() {
- fin.sync_with_stdio(false);
- fout.sync_with_stdio(false);
- fin.tie(nullptr);
- fout.tie(nullptr);
- int M;
- fin >> N >> M >> source >> sink;
- Graph.resize(N + 1);
- Capacity = Cost = vector < vector < int > >(N + 1, vector < int >(N + 1));
- while(M--) {
- int u, v, capacity, w;
- fin >> u >> v >> capacity >> w;
- Graph[u].emplace_back(v);
- Graph[v].emplace_back(u);
- Capacity[u][v] = capacity;
- Cost[u][v] = w;
- Cost[v][u] = -w;
- }
- fout << min_cost_flow();
- }
Advertisement
Add Comment
Please, Sign In to add comment