Cod sursa(job #1166773)

Utilizator misu007Pogonaru Mihai misu007 Data 3 aprilie 2014 20:11:39
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;

int n,viz[1001],drum[1001];//f[1001][1001],c[1001][1001];

const int inf=0x3f3f3f3f;

struct nod
{
    nod *u;
    int x;
}*a[1001];

queue <int> q;

void adauga(int x,int y,int z)
{
    nod *nd=new nod;
    nd->x=y;
    nd->u=a[x];
    c[x][y]=z;
    a[x]=nd;
}

void read()
{
    freopen("maxflow.in","r",stdout);
    int m,x,y,z;
    scanf("%d%d",&n,&m);
    while(m)
    {
        --m;
        scanf("%d%d%d",&x,&y,&z);
        adauga(x,y,z);
        adauga(y,x,0);
    }
}

int bfs()
{
    int x,y;
    nod *nd;
    q.push(1);
    memset(viz,0,sizeof(viz));
    viz[1]=1;
    while(!q.empty())
    {
        if(q.front()!=n)
        {
            x=q.front();
            y=nd->x;
            nd=a[x];
            while(nd)
            {
                if(f[x][y]<c[x][y]&&!viz[y])
                {
                    q.push(y);
                    viz[y]=1;
                    drum[y]=x;
                }
                nd=nd->u;
            }
        }
        q.pop();
    }
    return viz[n];
}

int main()
{
    read();
    int flow=0,flowm,i;
    nod *nd;
    freopen("maxflow.out","w",stdout);
    while(bfs())
    {
        nd=a[n];
        while(nd)
        {
            if(f[nd->x][n]<c[nd->x][n]&&viz[nd->x])
            {
                drum[n]=nd->x;
                flowm=inf;
                for(i=n;i!=1;i=drum[i])
                {
                    flowm=min(flowm,c[drum[i]][i]-f[drum[i]][i]);
                }
                if(flowm)
                {
                    for(i=n;i!=1;i=drum[i])
                    {
                        f[drum[i]][i]+=flowm;
                        f[i][drum[i]]-=flowm;
                    }
                    flow+=flowm;
                }
            }
            nd=nd->u;
        }
    }
    printf("%d\n",flow);
    return 0;
}