Pagini recente » Clasamentul arhivei de probleme | Cod sursa (job #3144240)
#include <bits/stdc++.h>
#define cin in
#define cout out
#define ll long long
#define eb emplace_back
#define pii pair<int, int>
#define tpl tuple<int, int, int>
using namespace std;
const string file_name("maxflow");
ifstream in(file_name + ".in");
ofstream out(file_name + ".out");
int n,k,x,y,c,lvl[1005];
unsigned p[1005];
ll cost[1005][1005];
vector<int> g[1005];
bool bfs(int s,int t)
{
memset(lvl,0,sizeof(lvl));
memset(p,0,sizeof(p));
queue<int> q;
lvl[s]=1;
q.push(s);
/// elimin muchiile saturate
for(int i=1;i<=n;i++)
{
bool ok=1;
while(ok)
{
ok=0;
unsigned j=0;
for(j=0;j<g[i].size() and !ok;j++)
if(cost[i][g[i][j]]==0)
ok=1;
j--;
if(ok)
{
g[i].erase(g[i].begin()+j);
}
}
}
while(!q.empty())
{
int k=q.front();
q.pop();
for(auto x: g[k])
if(cost[k][x]>0 and lvl[x]==0)
{
lvl[x]=lvl[k]+1;
q.push(x);
}
}
return lvl[t]!=0;
}
int sendflow(int k,ll flow)
{
if(k==n or flow==0) return flow;
while(p[k]<g[k].size())
{
int x=g[k][p[k]];
p[k]++;
if(lvl[x]==lvl[k]+1 and cost[k][x]>0)
{
ll minflow=min(flow,cost[k][x]);
ll revflow=sendflow(x,minflow);
if(revflow!=0)
{
cost[k][x]-=revflow;
cost[x][k]+=revflow;
return revflow;
}
}
}
return 0;
}
int main()
{
cin>>n>>k;
while(k--)
{
cin>>x>>y>>c;
g[x].eb(y);
g[y].eb(x);
cost[x][y]=c;
}
ll ans=0;
while(bfs(1,n))
{
while(ll flow=sendflow(1,LLONG_MAX))
{
ans+=flow;
}
}
cout<<ans;
return 0;
}