Cod sursa(job #788883)

Utilizator round2Test P round2 Data 15 septembrie 2012 23:52:11
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define Max 1001
#define Inf 0xffffff

vector<int>g[Max];
int n,c[Max][Max],f[Max][Max],t[Max],cd[Max];
bool was[Max];

bool bfs()
{
    int p,u,x,y;
    memset(was,0,sizeof(was));
    p=u=1; cd[1]=1; was[1]=1;
    while(p<=u)
    {
        x=cd[p++];
        for(int i=0;i<g[x].size();i++)
        {
            y=g[x][i];
            if(!was[y] && c[x][y]>f[x][y])
            {
                was[y]=1;
                t[y]=x;
                if(y!=n)cd[++u]=y;
            }
        }
    }
    return was[n];
}


void maxflow()
{
    int flux_t=0,flux;
    while(bfs())
    {
        for(int i=0;i<g[n].size();i++)
        if(was[g[n][i]])
        {
            t[n]=g[n][i];
            flux=Inf;
            for(int x=n;x!=1;x=t[x])flux=min(flux,c[t[x]][x]-f[t[x]][x]);
            if(flux!=0)
            {
                flux_t+=flux;
                for(int x=n;x!=1;x=t[x])
                {
                    f[t[x]][x]+=flux;
                    f[x][t[x]]-=flux;
                }
            }
        }
    }
    printf("%d\n",flux_t);
}

int main()
{
    int m,x,y,z;
    freopen("maxflow.in","r",stdin);
    freopen("maxflow.out","w",stdout);

        scanf("%d %d",&n,&m);
        while(m--)
        {
            scanf("%d %d %d",&x,&y,&z);
            g[x].push_back(y);
            g[y].push_back(x);
            c[x][y]=z;
        }
    maxflow();

    return 0;
}