Pagini recente » Cod sursa (job #2608342) | Cod sursa (job #455782) | Cod sursa (job #254963) | Cod sursa (job #2668906) | Cod sursa (job #2758887)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int MAX_N = 1 << 10;
vector<bool> BFS(const vector<vector<int>>& graph, const vector<vector<int>>& capacity, const vector<vector<int>>& flow, vector<int>& dads){
vector<bool> visited(graph.size(), false);
queue<int> Q;
Q.push(0);
visited[0] = true;
while(!Q.empty()){
int current_node = Q.front();
Q.pop();
if(current_node == graph.size() - 1)
continue;
for(auto adjacent : graph[current_node])
if(!visited[adjacent] && capacity[current_node][adjacent] > flow[current_node][adjacent]){
Q.push(adjacent);
visited[adjacent] = true;
dads[adjacent] = current_node;
}
}
return visited;
}
int main(){
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
int N, M, maxflow, result = 0;
vector<vector<int>> graph, capacity, flow;
vector<int> dads;
cin >> N >> M;
for(int i = 0; i < N; ++i){
graph.push_back({});
capacity.push_back(vector<int>(N, 0));
flow.push_back(vector<int>(N, 0));
dads.push_back(0);
}
for(int x, y, z; M > 0; --M){
cin >> x >> y >> z;
--x; --y;
graph[x].push_back(y);
graph[y].push_back(x);
capacity[x][y] = z;
}
vector<bool> visited = BFS(graph, capacity, flow, dads);
--N;
while(visited[N]){
for(auto adjacent : graph[N]){
if(visited[adjacent] && capacity[adjacent][N] > flow[adjacent][N]){
dads[N] = adjacent;
maxflow = INT32_MAX;
for(int i = N; i != 0; i = dads[i])
maxflow = min(maxflow, capacity[dads[i]][i] - flow[dads[i]][i]);
if(maxflow > 0){
for(int i = N; i != 0; i = dads[i]){
flow[dads[i]][i] += maxflow;
flow[i][dads[i]] -= maxflow;
}
result += maxflow;
}
}
}
fill(dads.begin(), dads.end(), 0);
visited = BFS(graph, capacity, flow, dads);
}
cout << result;
cin.close();
cout.close();
return 0;
}