Pagini recente » Cod sursa (job #2190993) | Cod sursa (job #182080) | Cod sursa (job #1540080) | Cod sursa (job #2190997) | Cod sursa (job #1082834)
#include <fstream>
#include <vector>
#include <queue>
#define NMax 1024
#define MMax 5010
#define INF 2000000000
using namespace std;
int ans;
int n, m;
int from[NMax];
vector <int> G[NMax];
int residual_graph[NMax][NMax];
int flow[NMax][NMax];
bool viz[NMax];
/// residual graph are la pozitia [i][j] pe x unde x este capacitatea - fluxul pe muchia i -> j
/// si are la pozitia [j][i] pe y unde y este fluxul pe i -> j daca acesta este > 0
void Read()
{
ifstream f("maxflow.in");
f>>n>>m;
for (int i = 1; i<=m; ++i)
{
int x, y, capacity;
f>>x>>y>>capacity;
// if (residual_graph[y][x] == 0)
{
G[x].push_back(y);
G[y].push_back(x);
}
residual_graph[x][y] = capacity;
}
f.close();
}
inline bool BFS()
{
queue <int> Q;
int i;
for (i=1; i<=n; ++i)
from[i] = 0, viz[i] = false;
Q.push(1);
viz[1] = true;
while(!Q.empty())
{
int node = Q.front(); Q.pop();
for (vector<int>::iterator it = G[node].begin(); it!=G[node].end(); ++it)
if (!viz[*it] && residual_graph[node][*it] > 0)
{
from[*it] = node;
viz[*it] = true;
Q.push(*it);
}
}
return viz[n];
}
void Solve()
{
while (BFS()) /// cat timp mai am cai de augmentare
{
int i;
for (i=2; i<n; ++i)
if (residual_graph[i][n] > 0 && from[i])
{
int localflow = residual_graph[i][n];
int node = i;
while (node != 1)
{
localflow = min(localflow, residual_graph[from[node]][node]);
node = from[node];
}
ans += localflow;
/// poate am saturat o muchie mai inainte in arborele BFS si acum nu mai are rost sa fac vreo ceva
if (localflow == 0)
continue;
node = i;
residual_graph[i][n] -= localflow;
residual_graph[n][i] += localflow;
flow[i][n] += localflow;
while (node != 1)
{
flow[i][n] += localflow;
residual_graph[from[node]][node] -= localflow;
residual_graph[node][from[node]] += localflow;
node = from[node];
}
}
}
}
void Write()
{
ofstream g("maxflow.out");
g<<ans<<"\n";
g.close();
}
int main()
{
Read();
Solve();
Write();
return 0;
}