Pagini recente » Cod sursa (job #971006) | Cod sursa (job #834046) | Cod sursa (job #3330552) | Cod sursa (job #757296) | Cod sursa (job #3336636)
#include <iostream>
#include <vector>
#include <queue>
#define pii pair<int, int>
using namespace std;
const int NMAX = 1005;
const char nl = '\n';
const int INF = 1e9 + 7;
vector<int> graph[NMAX];
vector<int> rev_graph[NMAX];
int flow[NMAX][NMAX]; // fluxul actual pe arce
int capacity[NMAX][NMAX]; // capacitatea pe arce
int father[NMAX]; // pentru a putea parcurge drumul inapoi
int visited[NMAX];
bool bfs(int n) {
for(int i = 1; i <= n; ++i) {
father[i] = 0;
visited[i] = 0;
}
queue<int> q;
int source = 1;
visited[source] = 1;
q.push(source);
while(!q.empty()) {
auto curr_node = q.front();
q.pop();
for(auto neigh: graph[curr_node]) {
if(visited[neigh] == 0 && capacity[curr_node][neigh] - flow[curr_node][neigh] > 0) {
father[neigh] = curr_node; // tata pozitiv => arc direct
visited[neigh] = 1;
q.push(neigh);
if(neigh == n) {
return true;
}
}
}
for(auto neigh: rev_graph[curr_node]) {
if(visited[neigh] == 0 && flow[curr_node][neigh] > 0) {
father[neigh] = -curr_node; // tata negativ => arc invers
visited[neigh] = 1;
q.push(neigh);
if(neigh == n) {
return true;
}
}
}
}
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
int n, m;
cin >> n >> m;
for(int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back(v);
rev_graph[v].push_back(u);
capacity[u][v] = w;
}
int max_flow = 0;
while(bfs(n)) {
int node = n;
int residual_capacity = INF;
while(node != 1) {
if(father[node] > 0) {
residual_capacity = min(residual_capacity, capacity[father[node]][node] - flow[father[node]][node]);
node = father[node];
} else {
residual_capacity = min(residual_capacity, flow[node][-father[node]]);
node = -father[node];
}
}
node = n;
while(node != 1) {
if(father[node] > 0) {
flow[father[node]][node] += residual_capacity;
node = father[node];
} else {
flow[node][-father[node]] -= residual_capacity;
node = -father[node];
}
}
max_flow += residual_capacity;
}
cout << max_flow << nl;
return 0;
}