Pagini recente » Cod sursa (job #1773289) | Cod sursa (job #1556541) | Cod sursa (job #648320) | Cod sursa (job #1092128) | Cod sursa (job #1020848)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <limits.h>
using namespace std;
int n,m;
vector<int> adjacencyList[1024];
int flow[1024][1024];
int capacities[1024][1024];
int visited[1024];
int prevv[1024];
int bfs(int startNode){
queue<int> q;
for (int i=1; i<=n; i++){
visited[i] = 0;
}
q.push(startNode);
visited[startNode] = 1;
while (!q.empty()){
int currentNode = q.front();
q.pop();
if (currentNode != n){
for (int i=0; i< adjacencyList[currentNode].size(); i++){
int nextNode = adjacencyList[currentNode][i];
if (!visited[nextNode] &&
(capacities[currentNode][nextNode] - flow[currentNode][nextNode]) > 0 ){
visited[nextNode] = 1;
prevv[nextNode] = currentNode;
q.push(nextNode);
}
}
}
}
return visited[n];
}
int main()
{
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
scanf("%d %d", &n, &m);
int from, to, cost;
for (int i=0; i<m; i++){
scanf("%d %d %d", &from, &to, &cost);
adjacencyList[from].push_back(to);
adjacencyList[to].push_back(from);
capacities[from][to] = cost;
}
//work
long long sum = 0;
while (bfs(1)){
for (int i=1; i<=n-1; i++){
if (visited[i] && (capacities[i][n] - flow[i][n]) > 0){
int currentNode = n;
int minn = INT_MAX;
prevv[n] = i;
while (currentNode != 1){
if (minn > capacities[prevv[currentNode]][currentNode] - flow[prevv[currentNode]][currentNode]){
minn = capacities[prevv[currentNode]][currentNode] - flow[prevv[currentNode]][currentNode];
}
currentNode = prevv[currentNode];
}
currentNode = n;
if (minn > 0){
while (currentNode != 1){
flow[prevv[currentNode]][currentNode] += minn;
flow[currentNode][prevv[currentNode]] -= minn;
currentNode = prevv[currentNode];
}
sum += minn;
}
}
}
}
/*
for (int i=1; i<=n-1; i++){
sum += flow[i][n];
}
*/
printf("%lld", sum);
return 0;
}