Pagini recente » Cod sursa (job #791897) | Cod sursa (job #1607418) | Cod sursa (job #23842) | Cod sursa (job #1612456) | Cod sursa (job #1678430)
#include <iostream>
#include <fstream>
#include <queue>
#define oo 2147483647
using namespace std;
int n;
int c[1005][1005];
bool vis[1005];
int tata[1005];
int mn[1005];
priority_queue<pair< int, int> > pq;
bool onPath() {
queue<int> q;
q.push(1);
vis[1] = true;
mn[1] = oo;
while(!q.empty()) {
int cur = q.front();
q.pop();
if(c[cur][n]) pq.push({min(mn[cur], c[cur][n]), cur});
for(int i = 2; i < n; i ++) {
if(c[cur][i] > 0 && !vis[i]) {
mn[i] = min(mn[cur], c[cur][i]);
vis[i] = true;
tata[i] = cur;
q.push(i);
}
}
}
while(!q.empty()) q.pop();
bool ok = false;
for(int i = 1; i < n; i ++) {
if(vis[i] && c[i][n] > 0) ok = true;
vis[i] = false;
}
return ok;
}
int minCap(int in) {
int i = in;
int mn = c[i][n];
for(; tata[i]; i = tata[i]) {
mn = min(mn, c[tata[i]][i]);
}
if(mn > 0) {
c[in][n] -= mn;
c[n][in] += mn;
for(; tata[in]; in = tata[in]) {
c[tata[in]][in] -= mn;
c[in][tata[in]] += mn;
}
}
return mn;
}
int flow;
void maxFlow() {
int capacity = 0;
while(true) {
if(!onPath()) break;
while(!pq.empty()) {
int cur = pq.top().second;
pq.pop();
int cost = minCap(cur);
if(cost > 0) flow += cost;
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int m, x, y;
f >> n >> m;
for(int i = 1; i <= m; i ++) {
f >> x >> y; f >> c[x][y];
}
maxFlow();
g << flow << "\n";
return 0;
}