Cod sursa(job #931480)

Utilizator PatrikStepan Patrik Patrik Data 28 martie 2013 11:42:07
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
    #include<cstdio>
    #include<vector>
    #include<queue>
    #include<cstring>
    using namespace std;
    #define MAX 1001
    #define pb push_back
    #define INF 110001
    int N , M  , c[MAX][MAX] , f[MAX][MAX] , p[MAX],fmin,flux;
    vector<int>G[MAX] , Gf[MAX];
    queue<int>Q;
    bool viz[MAX];

    void citire();
    void solve();
    void tipar();
    bool BDF();

    int main()
    {
        citire();
        solve();
        tipar();
        return 0;
    }


    void citire()
    {
        int x , y, cost;
        freopen("maxflow.in" , "r" , stdin );
        scanf("%d%d" , &N , &M );
        for(;M;--M)
        {
            scanf("%d%d%d" , &x , &y , &cost);
            G[x].pb(y);
            Gf[y].pb(x);
            c[x][y] = cost;
        }
    }

    void tipar()
    {
        freopen("maxflow.out" , "w" , stdout );
        printf("%d" , flux);
    }

    bool BDF()
    {
        memset(viz,0,sizeof(viz));
        Q.push(1);viz[1] = 1;
        for(;!Q.empty();Q.pop())
        {
            int n = Q.front();
            for(int j = 0 ; j < (int)G[n].size() ; ++j )
            {
                if(viz[G[n][j]] || f[n][G[n][j]] == c[n][G[n][j]])
                    continue;
                viz[G[n][j]] = 1;
                p[G[n][j]] = n;
                Q.push(G[n][j]);
            }
        }
        if(viz[N])return 1;
        return 0;
    }

    void solve()
    {
        while(BDF())
        {
            for(int j = 0 ; j < (int)Gf[N].size() ; ++j )
            {
                int n = Gf[N][j];
                if(f[n][N] == c[n][N])continue;
                p[N] = n;
                fmin = INF;
                for(int j = N;j!=1;j=p[j])
                    fmin = min(fmin,c[p[j]][j]-f[p[j]][j]);
                for(int j = N ; j!=1 ; j = p[j])
                    f[p[j]][j] += fmin;
                flux +=fmin;
            }
        }
    }