Pagini recente » Cod sursa (job #1671954) | Cod sursa (job #1587196) | Cod sursa (job #829806) | Cod sursa (job #536725) | Cod sursa (job #2955434)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");
class Graph
{
private:
long long maxFlow = 0;
vector<int> parent;
vector<bool> seen;
vector<vector<int>> graph;
vector<vector<int>> capacityFromXtoY;
int noOfVertices;
int noOfEdges;
int lastVertex;
public:
Graph(int n, int m)
{
noOfVertices = n;
noOfEdges = m;
lastVertex = n;
graph.resize(n+1);
capacityFromXtoY.resize(n+1);
for (int i = 1; i <=n; i++)
{
capacityFromXtoY[i].resize(n+1, 0);
}
parent.resize(n+1, 0);
seen.resize(n+1, 0);
}
void readEdges()
{
for(int i = 1; i <= noOfEdges; i++)
{
int x, y, v;
fin >> x >> y >> v;
capacityFromXtoY[x][y] = v;
graph[x].push_back(y);
graph[y].push_back(x);
}
}
bool bfs()
{
seen.assign(noOfVertices + 1, 0);
parent.assign(noOfVertices + 1, 0);
queue<int> que;
que.push(1);
seen[1] = true;
parent[1] = 1;
while (!que.empty())
{
int front = que.front();
que.pop();
if(front != lastVertex)
{
for(auto nvertex = graph[front].begin(); nvertex != graph[front].end(); nvertex++)
{
if(seen[*nvertex] == false && capacityFromXtoY[front][*nvertex] > 0)
{
que.push(*nvertex);
parent[*nvertex] = front;
seen[*nvertex] = true;
}
}
}
}
return seen[lastVertex];
}
int getMaxFlow()
{
while (this->bfs())
{
for(auto nvertex = graph[lastVertex].begin(); nvertex != graph[lastVertex].end(); nvertex++)
{
if(seen[*nvertex])
{
parent[lastVertex] = *nvertex;
int localMaxFlow = 1<<30;
int vrtx = lastVertex;
while(vrtx != 1)
{
localMaxFlow = min(localMaxFlow, capacityFromXtoY[parent[vrtx]][vrtx]);
vrtx = parent[vrtx];
}
if(localMaxFlow == 0)
{
continue;
}
vrtx = lastVertex;
while(vrtx != 1)
{
capacityFromXtoY[parent[vrtx]][vrtx] -= localMaxFlow;
capacityFromXtoY[vrtx][parent[vrtx]] += localMaxFlow;
vrtx = parent[vrtx];
}
maxFlow += localMaxFlow;
}
}
}
return maxFlow;
}
};
int main()
{
int n, m, result;
fin>>n>>m;
Graph graph (n,m);
graph.readEdges();
result = graph.getMaxFlow();
fout<<result;
return 0;
}