Pagini recente » Cod sursa (job #980134) | Cod sursa (job #1308819) | Cod sursa (job #275672) | Cod sursa (job #1539173) | Cod sursa (job #2053736)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
class flow
{
public:
flow(int n, int source, int dest)
{
this->source = source;
this->dest = dest;
this->n = n;
cap.resize(n + 1, vector<int>(n + 1));
flux.resize(n + 1, vector<int>(n + 1));
vecini.resize(n + 1);
viz.resize(n + 1);
father.resize(n + 1);
}
void AddEdge(int x, int y, int c)
{
if(cap[x][y] == 0)
{
vecini[x].push_back(y);
vecini[y].push_back(x);
}
cap[x][y] += c;
}
int GetMaxFlow()
{
int ret = 0;
BFS();
while(viz[dest])
{
for(auto nod:vecini[dest])
{
if(cap[nod][dest] == flux[nod][dest] || viz[nod] == false)
continue;
father[dest] = nod;
int mn = cap[father[dest]][dest] - flux[father[dest]][dest];
nod = father[dest];
while(nod != source)
{
mn = min(mn, cap[father[nod]][nod] - flux[father[nod]][nod]);
nod = father[nod];
}
nod = dest;
while(nod != source)
{
flux[father[nod]][nod] += mn;
flux[nod][father[nod]] -= mn;
nod = father[nod];
}
ret += mn;
}
BFS();
}
return ret;
}
private:
void BFS()
{
fill(viz.begin(), viz.end(), false);
queue<int> q;
q.push(source);
viz[source] = true;
while(q.empty() == false)
{
int nod = q.front();
q.pop();
if(nod == dest)
continue;
for(auto v:vecini[nod])
{
if(cap[nod][v] == flux[nod][v] || viz[v])
continue;
viz[v] = true;
q.push(v);
father[v] = nod;
}
}
}
int source, dest;
int n;
vector<bool> viz;
vector<vector<int> > vecini;
vector<vector<int> > cap;
vector<vector<int> > flux;
vector<int> father;
};
int main()
{
ifstream in("maxflow.in");
int n, m;
in >> n >> m;
flow gr(n, 1, n);
int x, y, z;
while(m--)
{
in >> x >> y >> z;
gr.AddEdge(x, y, z);
}
in.close();
int rasp = gr.GetMaxFlow();
ofstream out("maxflow.out");
out << rasp;
out.close();
return 0;
}