Pagini recente » Cod sursa (job #856158) | Cod sursa (job #182998) | Cod sursa (job #279809) | Cod sursa (job #1155226) | Cod sursa (job #2565631)
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define NMAX 1024
#define INF (1<<30)-1
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n,m,s;
vector<int> ma[NMAX];
int cap[NMAX][NMAX];
void citire()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y,c;
fin>>x>>y>>c;
cap[x][y] += c;
ma[x].push_back(y);
ma[y].push_back(x);
}
}
int bfs(int s, int t, vector<int>& parent) {
fill(parent.begin(), parent.end(), -1);
parent[s] = -2;
queue<pair<int, int> > q;
q.push({s, INF});
while (!q.empty()) {
int cur = q.front().first;
int flow = q.front().second;
q.pop();
for(int i=0;i<ma[cur].size();i++)
{
int next = ma[cur][i];
if (parent[next] == -1 && cap[cur][next]) {
parent[next] = cur;
int new_flow = min(flow, cap[cur][next]);
if (next == t)
return new_flow;
q.push({next, new_flow});
}
}
}
return 0;
}
int maxflow(int s, int t) {
int flow = 0;
vector<int> parent(n+1);
int new_flow;
while (new_flow = bfs(s, t, parent)) {
flow += new_flow;
int cur = t;
while (cur != s) {
int prev = parent[cur];
cap[prev][cur] -= new_flow;
cap[cur][prev] += new_flow;
cur = prev;
}
}
return flow;
}
int main()
{
citire();
fout<<maxflow(1,n);
}