Pagini recente » Cod sursa (job #1211359) | Cod sursa (job #3215430) | Cod sursa (job #1974439) | Cod sursa (job #1352275) | Cod sursa (job #1214797)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1024;
int graph[NMAX][NMAX];
int resid[NMAX][NMAX];
int shptr[NMAX];
bool vistd[NMAX];
int N, M;
int pfs()
{
priority_queue <pair <int, pair <int, int> > > pq;
pq.push(make_pair(INT_MAX, make_pair(0, 1)));
for (int i = 0; i < NMAX; ++i) {
vistd[i] = false;
shptr[i] = 0;
}
int res = 0;
while (!pq.empty()) {
int magp = pq.top().first;
int from = pq.top().second.first;
int node = pq.top().second.second;
pq.pop();
if (vistd[node]) {
continue;
}
vistd[node] = true;
shptr[node] = from;
if (node == N) {
res = 1;
}
vistd[node] = true;
for (int i = 1; i <= N; ++i) {
if (resid[node][i] > 0) {
if (true) {
pq.push(make_pair(min(magp, resid[node][i]), make_pair(node, i)));
}
}
}
}
return res;
}
int main()
{
ifstream in("maxflow.in");
ofstream out("maxflow.out");
in >> N >> M;
for (int a, b, c, i = 0; i < M; ++i) {
in >> a >> b >> c;
graph[a][b] = c;
}
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= N; ++j) {
if (graph[i][j] > 0) {
resid[i][j] = graph[i][j];
} else if (graph[j][i] > 0) {
resid[i][j] = 0;
} else {
resid[i][j] = -1;
}
}
}
int a = 0;
int flow = 0;
while (pfs() > 0) {
a = INT_MAX;
for (int i = 1; i < N; ++i) {
if (resid[i][N] > 0) {
int x = i;
a = resid[x][N];
bool not_good = false;
while (x != 1) {
a = min(a, resid[shptr[x]][x]);
x = shptr[x];
if (x == 0) {
not_good = true;
break;
}
}
if (not_good) continue;
x = i;
while (x != 1) {
resid[shptr[x]][x] -= a;
resid[x][shptr[x]] += a;
x = shptr[x];
}
flow += a;
}
}
}
out << flow << "\n";
return 0;
}