Pagini recente » Cod sursa (job #2981175) | Cod sursa (job #1974594) | Cod sursa (job #2815380) | Cod sursa (job #2176082) | Cod sursa (job #2746352)
#include <bits/stdc++.h>
#define nmax 1005
#define inf 1000000009
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
vector<int> lista[nmax];
vector<int> adj[nmax];
int flow[nmax][nmax], capacity[nmax][nmax], level[nmax], ptr[nmax];
int n,m;
queue<int> q;
bool bfs(int start, int end){
for(int i=0; i<=n; i++){
level[i] = 0;
ptr[i] = 0;
}
level[start] = 1;
q.push(start);
while(!q.empty()){
int nod = q.front();
q.pop();
for(auto neigh: lista[nod]){
if(!level[neigh] && capacity[nod][neigh] > flow[nod][neigh]){
level[neigh] = level[nod] + 1;
q.push(neigh);
}
}
}
return level[end];
}
int dfs(int node, int end, int flw){
if(node == end){
return flw;
}
for(;ptr[node] < lista[node].size(); ptr[node]++){
int neigh = lista[node][ptr[node]];
if(level[node] + 1 == level[neigh] && capacity[node][neigh] > flow[node][neigh]){
int cur_flow = min(flw, capacity[node][neigh] - flow[node][neigh]);
int temp_flow = dfs(neigh, end, cur_flow);
if(temp_flow > 0){
flow[node][neigh] += temp_flow;
flow[neigh][node] -= temp_flow;
return temp_flow;
}
}
}
return 0;
}
int Dinic(int s, int t){
if(s == t) return -1;
int total = 0;
while(bfs(s,t)){
while(int fl = dfs(s,t,inf)){
total += fl;
}
}
return total;
}
int main(){
in >> n;
in >> m;
for(int i=0; i<m; i++){
int x, y;
in >> x >> y;
if(!capacity[x][y] && !capacity[y][x]){
lista[x].push_back(y);
lista[y].push_back(x);
}
in >> capacity[x][y];
}
out << Dinic(1, n) << '\n';
return 0;
}