Pagini recente » Cod sursa (job #2319911) | Cod sursa (job #2974128) | Cod sursa (job #2999481) | Cod sursa (job #2987028) | Cod sursa (job #3168255)
#include <bits/stdc++.h>
#define cin in
#define cout out
#define eb emplace_back
#define pii pair<int, int>
#define ll long long
using namespace std;
const string fn("maxflow");
ifstream in(fn + ".in");
ofstream out(fn + ".out");
const int MAX=1e3;
int n,k,lvl[MAX+5],ind[MAX+5];
ll cost[MAX+5][MAX+5];
vector<int> G[MAX+5];
void read()
{
cin>>n>>k;
for(int i=1,x,y,w;i<=k;i++)
{
cin>>x>>y>>w;
G[x].eb(y);
G[y].eb(x);
cost[x][y]=w;
}
}
bool bfs(int src,int dst)
{
queue<int> q;
q.emplace(src);
memset(lvl,0,sizeof(lvl));
memset(ind,0,sizeof(ind));
lvl[src]=1;
while(!q.empty())
{
int node=q.front();
q.pop();
for(auto x: G[node])
if(cost[node][x]>0 and lvl[x]==0)
lvl[x]=lvl[node]+1,q.emplace(x);
}
return lvl[dst]!=0;
}
ll sendflow(int node,ll flow)
{
if(node==n or flow==0) return flow;
while(ind[node]<G[node].size())
{
int x=G[node][ind[node]];
ind[node]++;
if(lvl[node]+1==lvl[x] and cost[node][x]>0)
{
ll minflow=min(cost[node][x],flow);
ll revflow=sendflow(x,minflow);
if(revflow!=0)
{
cost[node][x]-=revflow;
cost[x][node]+=revflow;
return revflow;
}
}
}
return 0;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
read();
ll ans=0;
while(bfs(1,n))
{
while(ll val=sendflow(1,LLONG_MAX))
ans+=val;
}
cout<<ans;
return 0;
}