Pagini recente » Cod sursa (job #906363) | Cod sursa (job #1817873) | Cod sursa (job #2751261) | Cod sursa (job #138038) | Cod sursa (job #2272540)
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
struct Gowiththeflow
{
int y,z;
};
vector<Gowiththeflow> g[1005];
struct Chiuveta
{
int nod,minn;
};
int last[1005];
int viz[1005];
int n,gasesc_drum;
const int INF = 2000000000;
bool cmp(Gowiththeflow a, Gowiththeflow b)
{
return a.y<b.y;
}
int bs(int i, int st, int dr, int val)
{
int med;
while(st<=dr){
med=(st+dr)/2;
if(g[i][med].y==val)
return med;
else{
if(g[i][med].y>val)
dr=med-1;
else
st=med+1;
}
}
}
int bfs(int nod)
{
queue<Chiuveta> q;
memset(viz, 0, sizeof(viz));
q.push({nod, INF});
viz[nod]=1;
memset(last, 0, sizeof(last));
while(!q.empty() && q.front().nod!=n){
Chiuveta u=q.front();
for(int i=0; i<g[u.nod].size(); i++)
if(viz[g[u.nod][i].y]==0 && g[u.nod][i].z>0){
q.push({g[u.nod][i].y, min(u.minn, g[u.nod][i].z)});
last[g[u.nod][i].y]=u.nod;
viz[g[u.nod][i].y]=1;
}
q.pop();
}
if(q.empty()){
gasesc_drum=0;
return 0;
}
else{
nod=n;
while(nod!=1){
g[last[nod]][bs(last[nod], 0, g[last[nod]].size()-1, nod)].z-=q.front().minn;
g[n][bs(nod, 0, g[nod].size()-1, last[nod])].z+=q.front().minn;
nod=last[nod];
}
return q.front().minn;
}
}
int main()
{ freopen("maxflow.in", "r",stdin);
freopen("maxflow.out", "w",stdout);
int m,i,x,y,z;
long long flux=0;
scanf("%d%d", &n, &m);
for(i=1; i<=m; i++){
scanf("%d%d%d", &x, &y, &z);
g[x].push_back({y,z});
g[y].push_back({x,0});
}
for(i=1; i<=n; i++)
sort(g[i].begin(), g[i].end(),cmp);
do{
gasesc_drum=1;
flux+=bfs(1);
/*for(i=1; i<=n; i++)
for(int j=0; j<g[i].size(); j++)
printf("%d %d %d\n",i, g[i][j].y, g[i][j].z);
return 0; */
}while(gasesc_drum==1);
printf("%lld", flux);
return 0;
}