Pagini recente » Cod sursa (job #1371391) | Cod sursa (job #1719002) | Cod sursa (job #2284568) | Cod sursa (job #170764) | Cod sursa (job #2884787)
#include <bits/stdc++.h>
using namespace std;
class Graph{
public:
const int N;
vector<vector<int>> neighbors;
vector<vector<int>> capacity;
public:
Graph(const int& N): N(N){
neighbors.resize(N);
capacity.assign(N, vector<int>(N));
}
void addEdge(int x, int y, int c){
neighbors[x].push_back(y);
neighbors[y].push_back(x);
capacity[x][y] = c;
}
int computeMaxCapacity() const{
int maxCapacity = capacity[0][0];
for(int i = 0; i < N; ++i){
for(int j = 0; j < N; ++j){
maxCapacity = max(maxCapacity, capacity[i][j]);
}
}
return maxCapacity;
}
};
class FordFulkerson{
private:
const Graph& G;
const int N;
const int SRC;
const int DEST;
vector<vector<int>> f;
vector<bool> vis;
int augmentingPath(int node, int minDelta, const int& CAPACITY_THRESHOLD){
if(vis[node]){
return 0;
}
vis[node] = true;
if(node == DEST){
return minDelta;
}
for(int nextNode: G.neighbors[node]){
int remainingCapacity = G.capacity[node][nextNode] - f[node][nextNode];
if(remainingCapacity >= CAPACITY_THRESHOLD){
int delta = augmentingPath(nextNode, min(minDelta, remainingCapacity), CAPACITY_THRESHOLD);
if(delta > 0){
f[node][nextNode] += delta;
f[nextNode][node] -= delta;
return delta;
}
}
}
return 0;
}
public:
FordFulkerson(const Graph& G, const int& SRC, const int& DEST):
G(G), N(G.N), SRC(SRC), DEST(DEST){
}
int computeMaxFlowWithScaling(){
f.assign(N, vector<int>(N, 0));
vis.assign(N, false);
int maxFlow = 0;
int capacityThreshold = G.computeMaxCapacity();
while(capacityThreshold > 0){
bool containsAugmentingPath = true;
while(containsAugmentingPath){
fill(vis.begin(), vis.end(), false);
int delta = augmentingPath(SRC, INT_MAX, capacityThreshold);
if(delta > 0){
maxFlow += delta;
}else{
containsAugmentingPath = false;
}
}
capacityThreshold /= 2;
}
return maxFlow;
}
};
int main(){
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
int N, M;
cin >> N >> M;
Graph G(N);
int x, y, c;
for(int i = 0; i < M; ++i){
cin >> x >> y >> c;
G.addEdge(x - 1, y - 1, c);
}
cout << FordFulkerson(G, 0, N - 1).computeMaxFlowWithScaling();
cin.close();
cout.close();
return 0;
}