Pagini recente » Cod sursa (job #806607) | Cod sursa (job #2928814) | Cod sursa (job #806604) | Cod sursa (job #799505) | Cod sursa (job #3337240)
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int INF = 1e9;
int N, M;
vector<vector<int>> adj;
vector<vector<int>> capacity;
bool bfs(int s, int t, vector<int>& parent){
fill (parent.begin(), parent.end(), -1);
queue<int> Q;
Q.push(s);
parent[s] = -2; // Marcăm sursa vizitată (valoare diferită de -1)
while(Q.size() > 0){
int u = Q.front();
Q.pop();
if(u == t)
return true;
for (auto vecin : adj[u]){
if (parent[vecin] == -1 && capacity[u][vecin] > 0 ){
parent[vecin] = u;
Q.push(vecin);
}
}
}
return false;
}
int main(){
fin >> N >> M;
adj.resize(N+1);
capacity.assign(N+1, vector<int>(N+1,0));
for (int i = 0 ; i < M ; i++){
int u, v, c;
fin >> u >> v >> c;
adj[u].push_back(v);
adj[v].push_back(u);
capacity[u][v] = c;
}
int max_flow = 0;
vector<int> parent(N+1);
while(bfs(1, N, parent)){
int path_flow = INF;
for(int v = N ; v != 1 ; v = parent[v]){
int u = parent[v];
path_flow = min(path_flow, capacity[u][v]);
}
for (int v = N ; v!= 1 ; v = parent[v]){
int u = parent[v];
capacity[u][v] -= path_flow;
capacity[v][u] += path_flow;
}
max_flow +=path_flow;
}
fout << max_flow;
}