Pagini recente » Cod sursa (job #2213926) | Cod sursa (job #2644193) | Cod sursa (job #1802808) | Cod sursa (job #2532246) | Cod sursa (job #2658893)
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int N, new_flow;
vector < vector < int > > Capacity, Flow, G;
inline void min_self(int& a, int b) {
a = min(a, b);
}
bool BFS(int source, int sink, vector < int >& parent) {
fill(parent.begin(), parent.end(), -1);
parent[source] = -2;
queue < int > Q;
Q.emplace(source);
while(!Q.empty()) {
int curr = Q.front();
Q.pop();
for(int next : G[curr])
if(parent[next] == -1 && Capacity[curr][next] > Flow[curr][next]) {
parent[next] = curr;
min_self(new_flow, Capacity[curr][next] - Flow[curr][next]);
if(next == sink)
return true;
Q.emplace(next);
}
}
return false;
}
int max_flow(int source, int sink) {
int flow = 0;
new_flow = INF;
vector < int > parent(N + 1);
while(BFS(source, sink, parent)) {
int node = sink;
while(node != source) {
Flow[parent[node]][node] += new_flow;
Flow[node][parent[node]] -= new_flow;
node = parent[node];
}
flow += new_flow;
new_flow = INF;
}
return flow;
}
int main() {
fin.sync_with_stdio(false);
fout.sync_with_stdio(false);
fin.tie(nullptr);
fout.tie(nullptr);
int M;
fin >> N >> M;
Capacity = Flow = vector < vector < int > >(N + 1, vector < int >(N + 1));
G.resize(N + 1);
while(M--) {
int u, v, w;
fin >> u >> v >> w;
Capacity[u][v] += w;
G[u].emplace_back(v);
G[v].emplace_back(u);
}
fout << max_flow(1, N);
}