Pagini recente » Borderou de evaluare (job #2731521) | Borderou de evaluare (job #1151417) | Borderou de evaluare (job #1550456) | Borderou de evaluare (job #1310268) | Cod sursa (job #3337055)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
const int INF = INT_MAX, NMAX = 1005;
int N, M, capacity[NMAX][NMAX];
bool v[NMAX];
vector<int> adj[NMAX];
int bfs(int s, int t, vector<int>& parent){
fill(parent.begin(), parent.end(), -1);
parent[s] = -2;
queue<pair<int, int>> q;
q.push({s, INF});
while(!q.empty()){
int curr = q.front().first;
int flow = q.front().second;
q.pop();
for(int& next : adj[curr]){
if(parent[next] == -1 && capacity[curr][next]){
parent[next] = curr;
int new_flow = min(flow, capacity[curr][next]);
if(next == t)
return new_flow;
q.push({next, new_flow});
}
}
}
return 0;
}
int maxflow(int s, int t){
int flow = 0;
vector<int> parent(NMAX);
int new_flow;
while(new_flow = bfs(s, t, parent)){
flow += new_flow;
int curr = t;
while(curr != s){
int prev = parent[curr];
capacity[prev][curr] -= new_flow;
capacity[curr][prev] += new_flow;
curr = prev;
}
}
return flow;
}
int main(){
f >> N >> M;
for(int i = 1; i <= M; i++){
int x, y, cost;
f >> x >> y >> cost;
adj[x].push_back(y);
capacity[x][y] = cost;
adj[y].push_back(x);
capacity[y][x] = 0;
}
g << maxflow(1, N);
return 0;
}