Pagini recente » Cod sursa (job #2262917) | Cod sursa (job #2944006) | Cod sursa (job #1212447) | Cod sursa (job #1107111) | Cod sursa (job #1869787)
#include <cstdio>
#include <vector>
#include <queue>
#define INF 999999999
using namespace std;
queue <int> Q;
vector <int> lst;
vector <int> G[1005];
int t[1005],F[1005][1005],C[1005][1005];
int n,x,y,cost,i,m;
bool bfs()
{
bool OK=false;
Q.push(1);
t[1]=-1;
while (!Q.empty())
{
int crt=Q.front();
Q.pop();
for (int i=0; i<G[crt].size(); i++)
{
if (G[crt][i]==n)
{
if (C[crt][n]>F[crt][n])
{
OK=true;
lst.push_back(crt);
}
continue;
}
if (!t[G[crt][i]] && C[crt][G[crt][i]]>F[crt][G[crt][i]])
{
Q.push(G[crt][i]);
t[G[crt][i]]=crt;
}
}
}
return OK;
}
int main()
{
freopen("maxflow.in","r",stdin);
freopen("maxflow.out","w",stdout);
scanf("%d %d",&n,&m);
for (i=1; i<=m; i++)
{
scanf("%d %d %d",&x,&y,&cost);
G[x].push_back(y);
C[x][y]+=cost;
G[y].push_back(x);
}
int flux=0;
while (bfs())
{
for (i=0; i<lst.size(); i++)
{
int nod=n;
int Min=INF;
t[n]=lst[i];
while (t[nod]!=-1)
{
Min=min(Min,C[t[nod]][nod]-F[t[nod]][nod]);
nod=t[nod];
}
flux+=Min;
nod=n;
while (t[nod]!=-1)
{
F[t[nod]][nod]+=Min;
F[nod][t[nod]]-=Min;
nod=t[nod];
}
}
for (i=1; i<=n; i++) t[i]=0;
while (!lst.empty()) lst.pop_back();
}
printf("%d\n",flux);
return 0;
}