Cod sursa(job #1658201)

Utilizator tudormaximTudor Maxim tudormaxim Data 21 martie 2016 10:42:33
Problema Flux maxim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;

ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");

const int nmax = 1005;
const int oo = (1<<30);
vector <int> g[nmax];
bitset <nmax> viz;
int c[nmax][nmax], f[nmax][nmax], dady[nmax], n, m;

bool bfs (int source, int dest)
{
    vector <int> :: iterator son;
    queue <int> q;
    int dad;
    viz=0;
    viz[source]=true;
    q.push(source);
    while(!q.empty())
    {
        dad=q.front();
        q.pop();
        for(son=g[dad].begin(); son!=g[dad].end(); son++)
            if(viz[*son]==false && c[dad][*son] > f[dad][*son])
            {
                dady[*son]=dad;
                viz[*son]=true;
                q.push(*son);
            }
    }
    return viz[dest];
}

void Edmunson_Karp (int source, int dest)
{
    vector <int> :: iterator son;
    int maxflow=0, flow, node;
    while(bfs(source, dest))
    {
        for(son=g[dest].begin(); son!=g[dest].end(); son++)
            if(viz[*son]==true && c[*son][dest] > f[*son][dest])
            {
                flow=oo;
                for(node=*son; dady[node]; node=dady[node])
                    flow=min(flow, c[dady[node]][node]-f[dady[node]][node]);

                maxflow+=flow;
                f[*son][dest]+=flow;
                f[dest][*son]-=flow;
                for(node=*son; dady[node]; node=dady[node])
                {
                    f[dady[node]][node]+=flow;
                    f[node][dady[node]]-=flow;
                }
            }

    }
    fout << maxflow << "\n";
}

int main()
{
    ios_base::sync_with_stdio(false);
    int x, y, cap, i;
    fin >> n >> m;
    for(i=1; i<=m; i++)
    {
        fin >> x >> y >> cap;
        c[x][y]+=cap;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    Edmunson_Karp(1, n);
    fin.close();
    fout.close();
    return 0;
}