Pagini recente » Cod sursa (job #2713660) | Cod sursa (job #1235196) | Cod sursa (job #289048) | Cod sursa (job #2270029) | Cod sursa (job #2693186)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
std::ifstream fin("maxflow.in");
std::ofstream fout("maxflow.out");
class Graph{
private:
int V, source, sink;
std::vector <std::vector <int>> edge;
std::vector <std::vector <int>> cap;
std::vector <int> parent;
std::vector <bool> visited;
bool bfs(){
std::queue <int> q;
std::fill(visited.begin(), visited.end(), false);
visited[source] = true;
q.push(source);
while(q.empty() == false){
int node = q.front();
q.pop();
if(node == sink) continue;
for(auto& next: edge[node]){
if(visited[next] == false and cap[node][next] > 0){
visited[next] = true;
q.push(next);
parent[next] = node;
}
}
}
return visited[sink];
}
public:
Graph(int size){
V = size;
edge.resize(V+2);
cap.resize(V+2);
for(auto& line: cap)
line.resize(V+2);
parent.resize(V+2);
visited.resize(V+2);
}
void addEdge(int src, int dest, int capacity, int weight){
edge[src].push_back(dest);
edge[dest].push_back(src);
cap[src][dest] = capacity;
}
int maxFlow(int src, int dest){
source = src;
sink = dest;
int maxFlow = 0, flow;
while(bfs() == true){
for(int& node: edge[sink]){
if(visited[node] == true and cap[node][sink] > 0){
parent[sink] = node;
flow = 1e9;
for(int curr = sink; curr != source; curr = parent[curr])
flow = std::min(flow, cap[parent[curr]][curr]);
for(int curr = sink; curr != source; curr = parent[curr]){
cap[parent[curr]][curr] -= flow;
cap[curr][parent[curr]] += flow;
}
maxFlow += flow;
}
}
}
return maxFlow;
}
};
void readInput(){
int V, E;
fin >> V >> E;
Graph graph(V);
for(int i=0, src, dest, cap, weight; i<E; i++){
fin >> src >> dest >> cap;
graph.addEdge(src, dest, cap, 0);
}
fout << graph.maxFlow(1, V);
}
int main(){
readInput();
return 0;
}