Pagini recente » Cod sursa (job #1128475) | Cod sursa (job #470635) | Cod sursa (job #639696) | Cod sursa (job #190113) | Cod sursa (job #2604682)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
struct GraphFlow {
vector<vector<int>> graph;
vector<vector<int>> capacity;
vector<vector<int>> flow;
GraphFlow(const vector<vector<int>> &graph, const vector<vector<int>> &capacity, const vector<vector<int>> &flow)
: graph(graph), capacity(capacity), flow(flow) {}
};
GraphFlow readGraph(const string & inputPath)
{
int n, m;
ifstream fin(inputPath);
fin >> n >> m;
int x, y, c;
vector<vector<int>> graph(n);
vector<vector<int>> capacity(n, vector<int>(n, 0));
vector<vector<int>> flow(n, vector<int>(n, 0));
for (int i = 0; i < m; i++)
{
fin >> x >> y >> c;
x --; y--;
graph[x].push_back(y);
capacity[x][y] = c;
graph[y].push_back(x);
capacity[y][x] = 0;
}
fin.close();
return GraphFlow(graph, capacity, flow);
}
void writeFlow(const string& outputPath, int flow)
{
ofstream fout (outputPath);
fout << flow;
fout.close();
}
vector<int> getDestinationInboundNodes(const vector<vector<int>> &graph, int destination)
{
vector<int> inboundNodes;
for (int i = 0; i < graph.size(); i++)
for (int j = 0; j < graph[i].size(); j++)
if (graph[i][j] == destination)
inboundNodes.push_back(i);
return inboundNodes;
}
void bfsTree(const vector<vector<int>> &graph, const vector<vector<int>> &capacity, const vector<vector<int>> &flow,
vector<int> & parent, int source)
{
fill(parent.begin(), parent.end(), -1);
queue<int> q;
q.push(source);
int x;
while (!q.empty())
{
x = q.front();
q.pop();
for (auto y : graph[x])
{
if (parent[y] == -1 && (capacity[x][y] - flow[x][y] > 0))
{
parent[y] = x;
q.push(y);
}
}
}
}
int computeMaxFlow(const GraphFlow& graphFlow, int source, int destination)
{
vector<vector<int>> graph = graphFlow.graph;
vector<vector<int>> capacity = graphFlow.capacity;
vector<vector<int>> flow = graphFlow.flow;
vector<int> parent(graph.size());
bfsTree(graph, capacity, flow, parent, source);
vector<int> destinationInNodes = getDestinationInboundNodes(graph, destination);
int totalFlow = 0;
int minFlow;
int srcNode, tarNode;
while (parent[destination] >= 0)
{
for (auto x: destinationInNodes)
if (parent[x] >= 0 && capacity[x][destination] - flow[x][destination] > 0)
{
minFlow = capacity[x][destination] - flow[x][destination];
srcNode = x;
tarNode = destination;
while (srcNode != -1)
{
minFlow = min(minFlow, capacity[srcNode][tarNode] - flow[srcNode][tarNode]);
tarNode = srcNode;
srcNode = parent[tarNode];
}
totalFlow += minFlow;
srcNode = x;
tarNode = destination;
while (srcNode != -1)
{
flow[srcNode][tarNode] += minFlow;
tarNode = srcNode;
srcNode = parent[tarNode];
}
}
bfsTree(graph, capacity, flow, parent, source);
}
return totalFlow;
}
int main()
{
auto graphFlow = readGraph("maxflow.in");
writeFlow("maxflow.out", computeMaxFlow(graphFlow, 0, graphFlow.graph.size() - 1));
return 0;
}