Cod sursa(job #1247956)

Utilizator bogdanpaunFMI Paun Bogdan Gabriel bogdanpaun Data 24 octombrie 2014 13:09:25
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int n , m , i , j ,x , y, z         ;
#define N 1024
int cost[N][N] , flux[N][N],st[N],tt[N];
bool viz[N];
struct nod{
    int val;
    nod *next;
};
nod *G[N],*tmp;

void add(int x,int y){
    nod *tmp = new nod;
    tmp->val = y;
    tmp->next = G[x];
    G[x] = tmp;
}
int bfs(){
    int i,j , x  ,y    ;
    st[0]=1;
    st[1]=1;
    memset(viz,0,sizeof(viz) );
    for(i=1;i<=st[0];++i){
        x = st[i];
        if(x == n) continue;
        tmp = G[x];
        for( ;tmp;tmp=tmp->next ){
           y = tmp->val;
           if(  cost[x][y] == flux[x][y] || viz[y] ) continue;
            viz[y] = 1;
            st[ ++st[0] ] = y;
            tt[y]=x;

        }
    }


    return viz[n];
}

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,&z);
        cost[x][y] += z;
        add(x,y);
        add(y,x);
    }

    int flow,fmin;
    for(flow=0; bfs();){
        tmp = G[n];
         for( ;tmp;tmp=tmp->next ){
        x = tmp->val;
        if( cost[x][n] == flux[x][n] || !viz[x] ) continue;
        tt[n]=x;
        fmin = 1<<29;
        for(x=n; x!=1; x = tt[x]){
            fmin = min(fmin , cost[ tt[x] ][x] - flux[ tt[x] ][x] );
        }
        if(fmin == 0) continue;
        for(x=n;x!=1;x=tt[x]){
            flux[ tt[x] ][x] +=fmin;
            flux[x][ tt[x] ] -=fmin;
        }
        flow+=fmin;
        }
    }
    printf("%d",flow);


    return 0;
}