Pagini recente » Cod sursa (job #173347) | Cod sursa (job #2861443) | Cod sursa (job #143418) | Cod sursa (job #2340614) | Cod sursa (job #1489010)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
ifstream f ("maxflow.in");
ofstream g ("maxflow.out");
const int MAX_NODES_COUNT = 1000;
const int MAX_EDGES_COUNT = 5000;
const int INF = (1 << 30);
int nodes_count, edges_count;
int source, destination;
int father[MAX_NODES_COUNT + 1];
int visited[MAX_NODES_COUNT + 1];
vector <int> graph[MAX_NODES_COUNT + 1];
int capacity[MAX_NODES_COUNT + 1][MAX_NODES_COUNT + 1], flow[MAX_NODES_COUNT + 1][MAX_NODES_COUNT + 1];
void read() {
int node1, node2, current_capacity;
f >> nodes_count >> edges_count;
for (int i = 1; i <= edges_count; ++i) {
f >> node1 >> node2 >> current_capacity;
capacity[node1][node2] += current_capacity;
graph[node1].push_back(node2);
graph[node2].push_back(node1);
}
}
bool BFS() {
int node, son, sons_count;
queue <int> Q;
for (int i = 1; i <= nodes_count; ++i)
visited[i] = false;
Q.push(source);
visited[source] = true;
while(!Q.empty()) {
node = Q.front();
Q.pop();
if (node == destination)
break;
sons_count = graph[node].size();
for (int i = 0; i < sons_count; ++i) {
son = graph[node][i];
if (!visited[son] && flow[node][son] < capacity[node][son]) {
visited[son] = true;
Q.push(son);
father[son] = node;
}
}
}
return visited[destination];
}
int max_flow() {
int sons_count, node, ant, minim, sol;
sol = 0;
while (BFS()) {
sons_count = graph[destination].size();
for (int i = 0; i < sons_count; ++i) {
node = graph[destination][i];
if (capacity[node][destination] <= flow[node][destination] || !visited[node]) continue;
father[destination] = node; node = destination;
minim = INF;
while (node != source) {
ant = father[node];
minim = min(minim, capacity[ant][node] - flow[ant][node]);
node = ant;
}
node = destination;
while (node != source) {
ant = father[node];
flow[node][ant] -= minim;
flow[ant][node] += minim;
node = ant;
}
sol += minim;
}
}
return sol;
}
int main() {
read();
source = 1;
destination = nodes_count;
g << max_flow() << '\n';
return 0;
}