Pagini recente » Cod sursa (job #1250330) | Cod sursa (job #42874) | Cod sursa (job #1865184) | Cod sursa (job #835756) | Cod sursa (job #2956796)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#define NMAX 1001
#define INF 0x7fffffff
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int n, m;
vector<vector<int>> graph;
vector<vector<int>> flow;
vector<vector<int>> capacity;
bitset<NMAX> vis;
vector<int> father;
bool bfs(int start){
vis.reset();
father.resize(n+1, 0);
vis[start] = true;
queue<int> Q;
Q.push(start);
while (!Q.empty()){
int x = Q.front();
Q.pop();
for (int nod : graph[x]) {
if(capacity[x][nod] == flow[x][nod] || vis[nod])
continue;
vis[nod] = true;
Q.push(nod);
father[nod] = x;
if(nod == n)
return 1;
}
}
return false;
}
int main() {
in >> n >> m;
graph.resize(n+1);
capacity.resize(n+1, vector<int>(n + 1));
flow.resize(n+1, vector<int>(n + 1));
int x, y, f;
while (m--){
in >> x >> y >> f;
graph[x].push_back(y);
graph[y].push_back(x);
capacity[x][y] += f;
}
int sol = 0;
do{
if( !bfs(1) )
break;
for (auto nod : graph[n]) {
if(capacity[nod][n] == flow[nod][n] || vis[nod] == 0)
continue;
father[n] = nod;
int flowMin = INF;
for (int i = n; father[i] != 0; i = father[i]) {
flowMin = min(flowMin, capacity[father[i]][i] - flow[father[i]][i]);
}
if (flowMin == 0)
continue;
sol += flowMin;
for (int i = n; father[i] != 0; i = father[i]) {
flow[father[i]][i] += flowMin;
flow[i][father[i]] -= flowMin;
}
}
} while (1);
out << sol;
return 0;
}