Pagini recente » Cod sursa (job #2814061) | Cod sursa (job #3240356) | Cod sursa (job #2768425) | Cod sursa (job #3291530) | Cod sursa (job #1263660)
#include <fstream>
#include <vector>
#include <queue>
void read_input(std::vector<std::vector<int> > &graph, std::vector<std::vector<int> > &costs)
{
std::ifstream in("maxflow.in");
int n, m, u, v, c;
in >> n >> m;
graph = std::vector<std::vector<int> >(n + 1);
costs = std::vector<std::vector<int> >(n + 1);
for (int i = 1; i <= n; i++)
costs[i] = std::vector<int>(n + 1);
while (m--)
{
in >> u >> v >> c;
costs[u][v] = c;
graph[u].push_back(v);
graph[v].push_back(u);
}
in.close();
}
void bfs(const std::vector<std::vector<int> > &graph, const std::vector<std::vector<int> > &costs, int s, int d, std::vector<int> &nodes, std::vector<int> &parent)
{
parent = std::vector<int>(graph.size(), -1);
std::queue<int> q;
q.push(s);
parent[s] = 0;
while (!q.empty())
{
int e = q.front();
q.pop();
for (int i = 0; i < (int) graph[e].size(); i++)
{
if (costs[e][graph[e][i]] == 0)
continue;
if (graph[e][i] == d)
nodes.push_back(e);
else if (parent[graph[e][i]] == -1)
{
q.push(graph[e][i]);
parent[graph[e][i]] = e;
}
}
}
}
int alg(const std::vector<std::vector<int> > &graph, std::vector<std::vector<int> > &costs)
{
int ret = 0, u, v, s = 1, d = graph.size() - 1;
while (1)
{
std::vector<int> nodes, parent;
bfs(graph, costs, s, d, nodes, parent);
if (nodes.size() == 0)
break;
for (int i = 0; i < (int) nodes.size(); i++)
{
u = nodes[i], v = d;
int flux = costs[u][v];
while (u != 0)
flux = std::min(flux, costs[u][v]), v = u, u = parent[u];
ret += flux;
u = nodes[i], v = d;
while (u != 0)
{
costs[u][v] -= flux, costs[v][u] += flux;
v = u, u = parent[u];
}
}
}
return ret;
}
void write_output(int sol)
{
std::ofstream out("maxflow.out");
out << sol << '\n';
out.close();
}
int main()
{
std::vector<std::vector<int> > graph, costs;
read_input(graph, costs);
write_output(alg(graph, costs));
}