Cod sursa(job #1248759)

Utilizator bogdanpaunFMI Paun Bogdan Gabriel bogdanpaun Data 25 octombrie 2014 22:10:09
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

#define NN 1024


struct node{
    int val;
    node *next;
};
node *G[NN],*tmp;
int n , m , x , y , z , i ;
int st[NN] , ant[NN],cap[NN][NN],flux[NN][NN];
bool viz[NN];

void add(int &x,int &y){
    tmp = new node;
    tmp->val = y;
    tmp->next= G[x];
    G[x] = tmp;
}

bool bfs(){
    st[0] = st[1] = 1;
    memset( viz , NULL , sizeof(viz) );
    for( i = 1; i <= st[0] ; ++i ){
        x = st[i];
        if( x == n ) continue;
        for( tmp = G[ x]; tmp ; tmp = tmp->next ){
            y = tmp->val;
            if( cap[x][y] == flux[x][y] || viz[y] ) continue;
            viz[y] = true;
            ant[y] = x;
            st[ ++st[0] ] = y;
        }
    }
    return viz[n];
}

int main()
{
    freopen("maxflow.in" , "r", stdin);
    freopen("maxflow.out", "w", stdout);
    scanf("%d %d",&n,&m);
    while( m-- ){
        scanf("%d %d %d",&x,&y,&z);
        add( x , y );
        add( y , x );
        cap[x][y] += z;
    }
    int flow,fmin;
    for(flow=0;bfs();)
        for(tmp=G[n] ; tmp ; tmp = tmp->next ){
            x = tmp->val;
            if( flux[x][n] == cap[x][n] || !viz[x] ) continue;
            ant[n] = x;
            fmin = 1 << 30;
            for(x=n; x!=1; x= ant[x] )
                fmin = min(fmin , cap[ ant[x] ][x] - flux[ ant[x] ][x] );
            if( fmin == 0 ) continue;
            for(x=n; x!=1; x= ant[x]){
                flux[ ant[x] ][x] += fmin;
                flux[x][ ant[x] ] -= fmin;
            }
            flow += fmin;
        }
    printf("%d",flow);



    return 0;
}