Cod sursa(job #1397165)

Utilizator AeroHHorea Stefan AeroH Data 23 martie 2015 12:15:37
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define N 1005
using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int i,j,x,y,z,n,m,c[N][N],p[N],flow;
vector<int> v[N];
int bfs()
{
    memset(p,0,sizeof(p));
    p[1]=-1;
    queue<int> q;
    q.push(1);
    while(q.size())
        {
            int x=q.front();
            q.pop();
            for(int i=0;i<v[x].size();++i)
                {
                    int y=v[x][i];
                    if (c[x][y] > 0 && p[y] == 0)
                        {
                            p[y] = x;
                            q.push(y);
                        }
                }
        }
    return p[n];
}


int main()
{
    f>>n>>m;
    for (i=1;i<=m;++i)
        {
            f>>x>>y>>z;
            c[x][y]=z;
            v[x].push_back(y);
            v[y].push_back(x);
        }

    while(bfs())
        for(int j=0;j<v[n].size();++j)
                {
                    int x=v[n][j];
                    if (c[x][n] > 0 && p[x] != 0)
                    {
                        int cap=c[x][n];
                        for(i=x;i!=1;i=p[i])cap=min(cap,c[p[i]][i]);
                        for(i=x;i!=1;i=p[i])
                            {
                                c[p[i]][i]-=cap;
                                c[i][p[i]]+=cap;
                            }
                        c[x][n]-=cap;
                        flow+=cap;
                    }
                }

    g<<flow;
    return 0;
}