Pagini recente » Cod sursa (job #2144292) | Cod sursa (job #2759712) | Cod sursa (job #394960) | Cod sursa (job #933606) | Cod sursa (job #1488988)
#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];
int visited[MAX_NODES_COUNT];
vector <int> graph[MAX_NODES_COUNT];
int capacity[MAX_NODES_COUNT][MAX_NODES_COUNT];
int flow[MAX_NODES_COUNT][MAX_NODES_COUNT];
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[destination] = 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[node];
}
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;
}