Pagini recente » Cod sursa (job #878087) | Diferente pentru blog/bubblebubble intre reviziile 5 si 4 | Borderou de evaluare (job #2422961) | Cod sursa (job #557752) | Cod sursa (job #3337342)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
const int NMAX = 1005, INF = INT_MAX;
int capacity[NMAX][NMAX], N, M;
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 nod = q.front().first;
int flow = q.front().second;
q.pop();
for(int u : adj[nod])
if(parent[u] == -1 && capacity[nod][u]){
parent[u] = nod;
int new_flow = min(flow, capacity[nod][u]);
if(u == t)
return new_flow;
q.push({u, new_flow});
}
}
return 0;
}
int maxflow(int s, int t){
vector<int> parent(N + 1, -1);
int flow = 0, 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 u, v, cost;
f >> u >> v >> cost;
if(capacity[u][v] == 0 && capacity[v][u] == 0){
adj[u].push_back(v);
adj[v].push_back(u);
}
capacity[u][v] += cost;
}
g << maxflow(1, N);
return 0;
}