Pagini recente » Cod sursa (job #3351901) | Borderou de evaluare (job #2194250) | Cod sursa (job #952978) | Monitorul de evaluare | Cod sursa (job #3336271)
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int N,M;
vector<int> G[1001];
//nod_start (u) : {nod_destinatie (v): capacitate u-v}
unordered_map<int, unordered_map<int, int> > capacity; // memorie O(E)
int dfs(const vector<int> G[], vector<bool>& visited, int u, int t, int flow) {
// ajung la destinatie
if (u == t) return flow;
visited[u] = true;
for (int v : G[u]) {
if (!visited[v] && capacity[u][v] > 0) {
int currFlow = min(flow, capacity[u][v]);
int tempFlow = dfs(G, visited, v, t, currFlow);
if (tempFlow > 0) {
capacity[u][v] -= tempFlow;
capacity[v][u] += tempFlow;
return tempFlow;
}
}
}
return 0;
}
int FordFulkerson(vector<int> G[], int source, int sink) {
int maxflow = 0;
vector<bool> visited(1001);
while (true) {
int flow = dfs(G, visited, source, sink, INT_MAX); // cauta un drum, la inceput presupunem ca putem transporta oricat
if (flow == 0) break; // daca returneaza 0 nu mai exista drumuri
maxflow += flow;
fill(visited.begin(), visited.end(), false); // se reseteaza visited pentru urmatoarele iteratii
}
return maxflow;
}
int main() {
fin >> N >> M;
for (int i = 0; i < M; i++) {
int x,y,c;
fin >> x >> y >> c;
G[x].push_back(y);
G[y].push_back(x); // reverse edges
capacity[x][y] += c;
capacity[y][x] += 0;
}
int source = 1;
int sink = N;
fout << FordFulkerson(G,source, sink);
fout.close();
return 0;
}