Pagini recente » Cod sursa (job #1650651) | Cod sursa (job #988588) | Cod sursa (job #1798798) | Cod sursa (job #528259) | Cod sursa (job #2983767)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f ("maxflow.in");
ofstream g ("maxflow.out");
const int SIZE = 1005;
const int inf = 1000000000;
int n, m;
int capacity[SIZE][SIZE], flow[SIZE][SIZE];
// vector<vector<int>> capacity, flow;
vector<int> height(SIZE, 0), excess(SIZE, 0);
void push(int u, int v)
{
int d = min(excess[u], capacity[u][v] - flow[u][v]);
flow[u][v] += d;
flow[v][u] -= d;
excess[u] -= d;
excess[v] += d;
}
void relabel(int u)
{
int d = inf;
for (int i = 1; i <= n; i++) {
if (capacity[u][i] - flow[u][i] > 0)
d = min(d, height[i]);
}
if (d < inf)
height[u] = d + 1;
}
vector<int> find_max_height_vertices(int s, int t) {
vector<int> max_height;
for (int i = 1; i <= n; i++) {
if (i != s && i != t && excess[i] > 0) {
if (!max_height.empty() && height[i] > height[max_height[0]])
max_height.clear();
if (max_height.empty() || height[i] == height[max_height[0]])
max_height.push_back(i);
}
}
return max_height;
}
int max_flow(int s, int t)
{
// height.assign(n, 0);
height[s] = n;
// flow.assign(n, vector<int>(n, 0));
for (int i = 1; i <= n; i++)
{
flow[n][i] = 0;
}
// excess.assign(n, 0);
excess[s] = inf;
for (int i = 1; i <= n; i++) {
if (i != s)
push(s, i);
}
vector<int> current;
while (!(current = find_max_height_vertices(s, t)).empty()) {
for (int i : current) {
bool pushed = false;
for (int j = 1; j <= n && excess[i]; j++) {
if (capacity[i][j] - flow[i][j] > 0 && height[i] == height[j] + 1) {
push(i, j);
pushed = true;
}
}
if (!pushed) {
relabel(i);
break;
}
}
}
int max_flow = 0;
for (int i = 1; i <= n; i++)
max_flow += flow[i][t];
return max_flow;
}
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, z;
f >> x >> y >> z;
capacity[x][y] += z;
}
g << max_flow(1, n);
return 0;
}