Pagini recente » Cod sursa (job #2251037) | Cod sursa (job #2665730) | Cod sursa (job #1677956) | Cod sursa (job #3322515) | Cod sursa (job #3327835)
#include <fstream>
#include <vector>
using namespace std;
const int NMAX = 1000;
int flux[NMAX + 1][NMAX + 1], capacitate[NMAX + 1][NMAX + 1];
vector<int> G[NMAX + 1];
int vis[NMAX + 1], parent[NMAX + 1];
int n, m;
int bfs(int s, int d)
{
queue<int> q;
for (int i = 1; i <= n; i++)
vis[i] = 0;
q.push(s);
vis[s] = 1;
while(!q.empty())
{
int x = q.front();
q.pop();
for(auto y : G[x])
{
if(!vis[y] && capacitate[x][y] - flux[x][y] > 0)
{
vis[y] = 1;
q.push(y);
parent[y] = x;
if(y == d)
break;
}
}
}
if (!vis[d])
return 0;
vector<int> path;
int r = d;
while (r != 0)
{
path.push_back(r);
r = parent[r];
}
reverse(path.begin(), path.end());
int mn = 1e9;
for(int i = 0; i < path.size() - 1; i++)
{
int x = path[i];
int y = path[i + 1];
mn = min(mn, capacitate[x][y] - flux[x][y]);
}
for(int i = 0; i < path.size() - 1; i++)
{
int x = path[i];
int y = path[i + 1];
flux[x][y] += mn;
flux[y][x] -= mn;
}
return mn;
}
int main()
{
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
fin >> x >> y >> c;
capacitate[x][y] = c;
G[x].push_back(y);
G[y].push_back(x);
}
int sum = 0;
while(1)
{
int flux = bfs(1, n);
sum += flux;
if(flux == 0)
break;
}
fout << sum << "\n";
return 0;
}