Pagini recente » Cod sursa (job #2250238) | Cod sursa (job #1961112) | Cod sursa (job #1903147) | Cod sursa (job #1274397) | Cod sursa (job #2937072)
#include<bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int n, m, ii, tt, i, x, y, c, flow[1005][1005], capacity[1005][1005], rez, dad[1005], curr, max_add_flow, level[1005], capa[1005];
vector <int> v[1005];
bool seen[1005];
void dfs(int x)
{
//cout << "curr = " << x << " with level = " << level[x] << "\n";
seen[x] = true;
for(int i = 0; i < v[x].size(); i ++)
if(level[v[x][i]] == level[x] + 1 && !seen[v[x][i]] && capacity[x][v[x][i]] - flow[x][v[x][i]] > 0)
{
capa[v[x][i]] = min(capa[x], capacity[x][v[x][i]] - flow[x][v[x][i]]);
dad[v[x][i]] = x;
dfs(v[x][i]);
}
}
bool DFS()
{
memset(seen, 0, sizeof(seen));
dad[n] = -1;
capa[1] = INT_MAX;
dfs(1);
return dad[n] != -1;
}
void build_levels()
{
queue<int> Q;
Q.push(1);
level[1] = 1;
memset(seen, 0, sizeof(seen));
seen[1] = true;
while(!Q.empty())
{
int aux = Q.front();
Q.pop();
for(int i = 0; i < v[aux].size(); i ++)
{
int aux1 = v[aux][i];
if (!seen[aux1] && flow[aux][aux1] < capacity[aux][aux1])
{
level[aux1] = level[aux] + 1;
seen[aux1] = true;
Q.push(aux1);
}
}
}
}
void read()
{
f >> n >> m;
for(i = 1; i <= m; i ++)
{
f >> x >> y >> c;
v[x].push_back(y);
v[y].push_back(x);
capacity[x][y] = c;
}
}
void solve()
{
while(true)
{
build_levels();
bool flag = true;
while(DFS())
{
flag = false;
curr = n;
max_add_flow = capa[n];
curr = n;
while(curr != 1)
{
//cout << "curr = " << curr << " with level = " << level[curr] << "\n";
flow[dad[curr]][curr] += max_add_flow;
flow[curr][dad[curr]] -= max_add_flow;
curr = dad[curr];
}
//cout << max_add_flow << "\n";
rez += max_add_flow;
}
if(flag)
break;
}
}
void write()
{
g << rez << "\n";
f.close();
g.close();
}
int main()
{
//cin >> tt;
tt = 1;
for(ii = 1; ii <= tt; ii ++)
{
read();
solve();
write();
}
return 0;
}