Cod sursa(job #1495275)

Utilizator alexpetrescuAlexandru Petrescu alexpetrescu Data 2 octombrie 2015 20:40:45
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <cstdio>
#include <cstring>
#define INF 1000000000
#define MAXN 1000
#define MAXM 5000
int c[MAXN+1][MAXN+1], f[MAXN+1][MAXN+1], from[MAXN+1], n, q[MAXN+1], h, val[2*MAXM+1], next[2*MAXM+1], lista[MAXN+1];
inline void adauga(int x, int y){
    h++;
    val[h]=y;
    next[h]=lista[x];
    lista[x]=h;
}
inline bool bfs(){
    int st, dr, i, p;
    st=0;
    dr=1;
    q[0]=1;
    memset(from, 0, sizeof from);
    while(st<dr){
        for(p=lista[q[st]]; p; p=next[p]){
            i=val[p];
            if((i!=1)&&(from[i]==0)&&(c[q[st]][i]>f[q[st]][i])){
                from[i]=q[st];
                q[dr++]=i;
            }
        }
        if(from[n]!=0){
            return 1;
        }
        st++;
    }
    return 0;
}
int main(){
    int m, i, x, y, z, ans, min, p;
    FILE *fin, *fout;
    fin=fopen("maxflow.in", "r");
    fout=fopen("maxflow.out", "w");
    fscanf(fin, "%d%d", &n, &m);
    for(i=1; i<=m; i++){
        fscanf(fin, "%d%d%d", &x, &y, &z);
        adauga(x, y);
        adauga(y, x);
        c[x][y]=z;
    }
    while(bfs()){
        for(p=lista[n]; p; p=next[p]){
            if(from[val[p]]){
                min=c[val[p]][n]-f[val[p]][n];
                i=val[p];
                while(from[i]){
                    if(min>c[from[i]][i]-f[from[i]][i]){
                        min=c[from[i]][i]-f[from[i]][i];
                    }
                    i=from[i];
                }
                f[val[p]][n]+=min;
                f[n][val[p]]-=min;
                i=val[p];
                while(from[i]){
                    f[from[i]][i]+=min;
                    f[i][from[i]]-=min;
                    i=from[i];
                }
            }
        }
    }
    ans=0;
    for(i=1; i<n; i++){
        ans+=f[i][n];
    }
    fprintf(fout, "%d\n", ans);
    fclose(fin);
    fclose(fout);
    return 0;
}