Pagini recente » Cod sursa (job #434852) | Cod sursa (job #776857) | Cod sursa (job #1282025) | Cod sursa (job #496626) | Cod sursa (job #2886087)
#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<int> visIdOf;
int visId;
int augmentingPath(int node, int minDelta, const int& CAPACITY_THRESHOLD){
if(visIdOf[node] == visId){
return 0;
}
visIdOf[node] = visId;
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));
visIdOf.assign(N, 0);
visId = 0;
int maxFlow = 0;
int maxCapacity = G.computeMaxCapacity();
int capacityThreshold = 1;
while(capacityThreshold < maxCapacity){
capacityThreshold *= 2;
}
while(capacityThreshold > 0){
bool containsAugmentingPath = true;
while(containsAugmentingPath){
visId += 1;
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;
}