Cod sursa(job #1495419)

Utilizator alexpetrescuAlexandru Petrescu alexpetrescu Data 3 octombrie 2015 01:28:37
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <cstdio>
#include <cstring>
#define INF 1000000000
#define MAXN 1000
int n, from[MAXN+1], q[MAXN+1], v[MAXN+1][MAXN+1], f[MAXN+1][MAXN+1], c[MAXN+1][MAXN+1], viz[MAXN+1];
inline int bfs(){
    int st, dr, p, x;
    st=0;
    dr=1;
    q[0]=1;
    memset(from, 0, sizeof from);
    memset(viz, 0, sizeof viz);
    viz[1]=1;
    while((st<dr)&&(viz[n]==0)){
        for(p=1; p<=v[q[st]][0]; p++){
            x=v[q[st]][p];
            if((viz[x]==0)&&(c[q[st]][x]>f[q[st]][x])){
                from[x]=q[st];
                viz[x]=1;
                q[dr++]=x;
            }
        }
        st++;
    }
    return viz[n];
}
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);
        v[x][++v[x][0]]=y;
        v[y][++v[y][0]]=x;
        c[x][y]+=z;
    }
    while(bfs()){
        for(p=1; p<=v[n][0]; p++){
            x=v[n][p];
            if((viz[x])&&(c[x][n]>f[x][n])){
                from[n]=x;
                min=INF;
                i=n;
                while(i!=1){
                    if(min>c[from[i]][i]-f[from[i]][i]){
                        min=c[from[i]][i]-f[from[i]][i];
                    }
                    i=from[i];
                }
                i=n;
                while(i!=1){
                    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;
}