Pagini recente » Cod sursa (job #991032) | Cod sursa (job #2283260) | Cod sursa (job #1812514) | Cod sursa (job #1222919) | Cod sursa (job #2202571)
#include <bits/stdc++.h>
std::ifstream f("maxflow.in");
std::ofstream g("maxflow.out");
const int NMAX = 1005;
const int INF = INT_MAX;
std::vector <int> graph[NMAX]; /// graph[i] = the list of adjacent nodes to i
std::queue <int> nodeQueue; /// queue used for BFS
int flowCapacity[NMAX][NMAX]; /// flowCapacity[i][j] = the flow capacity from node i to node j
std::bitset <NMAX> visited; /// used for BFS tree optimization
int parent[NMAX]; /// used for BFS tree optimization
int numberOfNodes, numberOfEdges;
inline bool BFS(int sourceNode, int destinationNode){ /// returns 1 if any path from source to destination was found, 0 otherwise
int currentNode;
visited.reset(); /// clears the visited bitset for each new BFS
visited[sourceNode] = 1;
nodeQueue.push(sourceNode);
while (!nodeQueue.empty()){
currentNode = nodeQueue.front();
nodeQueue.pop();
if (currentNode == destinationNode)
continue;
for (const auto& nextNode : graph[currentNode]){
if (!visited[nextNode] && flowCapacity[currentNode][nextNode] > 0){
visited[nextNode] = 1;
parent[nextNode] = currentNode;
nodeQueue.push(nextNode);
}
}
}
return visited[destinationNode];
}
int MaxFlow(int sourceNode, int destinationNode){
int maxFlow = 0, minimumCapacity;
while (BFS(sourceNode, destinationNode)){
for (const auto& currentNode: graph[destinationNode]){ /// iterate through all nodes adjacent to the destination
if (!visited[currentNode] || flowCapacity[currentNode][destinationNode] <= 0) /// if the current node is not connected (or can't push flow into the destination) we skip it
continue;
parent[destinationNode] = currentNode;
minimumCapacity = INF;
for (int node = destinationNode; node != sourceNode; node = parent[node]){ /// find the edge with the minimum capacity in a path from source to destination
minimumCapacity = std::min(minimumCapacity, flowCapacity[parent[node]][node]);
}
for (int node = destinationNode; node != sourceNode; node = parent[node]){ /// update the edges in the residual graph
flowCapacity[node][parent[node]] += minimumCapacity;
flowCapacity[parent[node]][node] -= minimumCapacity;
}
//g<<minimumCapacity<<'\n';
maxFlow += minimumCapacity;
}
}
return maxFlow;
}
int main()
{
int nodeX, nodeY, currentFlow;
f>>numberOfNodes>>numberOfEdges;
for (int i=1; i<=numberOfEdges; i++){
f>>nodeX>>nodeY>>currentFlow;
graph[nodeX].push_back(nodeY);
graph[nodeY].push_back(nodeX);
flowCapacity[nodeX][nodeY]+=currentFlow;
}
g<<MaxFlow(1, numberOfNodes); /// by default 1 is the source node and n is the destination node
return 0;
}