Pagini recente » Cod sursa (job #2256100) | Cod sursa (job #2593917) | Cod sursa (job #557468) | Cod sursa (job #11371) | Cod sursa (job #2961798)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int residualGraph[1001][1001];
vector<vector<int>> adjList;
vector<int> tt;
int n, m;
void reset(vector<int>& v)
{
for(int i = 1; i <= n; ++i)
{
v[i] = 0;
}
v[1] = 1;
}
bool bfs()
{
reset(tt);
queue<int> q;
q.push(1);
while(!q.empty())
{
int crt = q.front();
q.pop();
for(int node : adjList[crt])
{
if(tt[node] == 0 && residualGraph[crt][node] > 0)
{
q.push(node);
tt[node] = crt;
if(node == n)
return true;
}
}
}
return false;
}
int getFlow()
{
int flow = INT_MAX;
int i = n;
while(i != 1)
{
flow = min(flow, residualGraph[tt[i]][i]);
i = tt[i];
}
return flow;
}
void updateResidual(int flow)
{
int i = n;
while(i != 1)
{
residualGraph[i][tt[i]] += flow;
residualGraph[tt[i]][i] -= flow;
i = tt[i];
}
}
int main()
{
fin>>n>>m;
tt.resize(n + 1);
adjList.resize(n + 1);
int x, y, z;
int res = 0;
for(int i = 0; i < m; ++i)
{
fin>>x>>y>>z;
residualGraph[x][y] = z;
residualGraph[y][x] = 0;
adjList[x].push_back(y);
adjList[y].push_back(x);
}
while(bfs())
{
int flow = getFlow();
res += flow;
updateResidual(flow);
}
fout<<res;
return 0;
}