Pagini recente » Cod sursa (job #1260867) | Cod sursa (job #292031) | Cod sursa (job #383691) | Cod sursa (job #2883445) | Cod sursa (job #2385044)
/*
* A computer is like air conditioning - it becomes useless when you
* open Windows.
* - Linus Torvalds
*/
#include <fstream>
#include <vector>
#include <memory>
#include <queue>
const int MAX_N = 1000;
struct Network
{
std::vector<int> neighbours[MAX_N];
int costs[MAX_N][MAX_N]{};
int nNodes = 0;
};
struct State
{
bool was[MAX_N];
int last[MAX_N];
int flux[MAX_N][MAX_N];
};
bool bfs(const Network&, State&, int source, int destination);
int flux_value(const Network& network, State& state, int x, int source);
void flux_update(State& state, int value, int x, int source);
int main()
{
std::ifstream fin("maxflow.in");
std::ofstream fout("maxflow.out");
std::unique_ptr<Network> network(new Network);
std::unique_ptr<State> state(new State);
int source, destination;
fin >> network->nNodes;
int m;
fin >> m;
for(int i = 0; i < m; i++)
{
int a, b, c;
fin >> a >> b >> c;
network->neighbours[a - 1].push_back(b - 1);
network->costs[a - 1][b - 1] = c;
network->neighbours[b - 1].push_back(a - 1);
}
source = 0;
destination = network->nNodes - 1;
int flux = 0;
while(bfs(*network, *state, source, destination))
{
auto x = flux_value(*network, *state, destination, source);
flux += x;
flux_update(*state, x, destination, source);
}
fout << flux;
return 0;
}
int flux_value(const Network& network, State& state, int x, int source)
{
int val = network.costs[state.last[x]][x] - state.flux[state.last[x]][x];
int y;
while(x != source)
{
y = state.last[x];
val = std::min(val, network.costs[y][x] - state.flux[y][x]);
x = y;
}
return val;
}
void flux_update(State& state, int value, int x, int source)
{
int y;
while(x != source)
{
y = state.last[x];
state.flux[y][x] += value;
state.flux[x][y] -= value;
x = y;
}
}
bool bfs(const Network& network, State& state, int source, int destination)
{
static std::queue<int> q;
for(int i = 0; i < network.nNodes; i++)
{
state.was[i] = false;
state.last[i] = -1;
}
q.push(source);
state.was[source] = true;
while(!q.empty())
{
int x = q.front();
q.pop();
if(x == destination)
return true;
for(auto y: network.neighbours[x])
{
if(!state.was[y] && state.flux[x][y] < network.costs[x][y])
{
state.last[y] = x;
state.was[y] = true;
q.push(y);
}
}
}
return state.was[destination];
}