Cod sursa(job #785654)

Utilizator round1First Round round1 Data 9 septembrie 2012 15:27:11
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
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));
    cd[p = u = 1] = 1;
    was[1] = 1;
    while(p <= u)
    {
        x = cd[p++];
      //  if(x == n)continue;
        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_max = 0,flux;
    int step =1;
    while( bfs() && step++ )
    {
        flux = Inf;
        for(int i=0;i<g[n].size();i++)
        if( was[g[n][i]] )
        {
            t[n] = g[n][i];
            for(int x = n;x != 1;x = t[x])flux = min(flux,c[t[x]][x] - f[t[x]][x]);
            if(flux != 0)
            {
                flux_max += flux;
                for(int x = n;x != 1;x = t[x])
                {
                    f[t[x]][x] += flux;
                    f[x][t[x]] -= flux;
                }
            }
        }
    }
    printf("%d\n",flux_max);
}

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;
}