Cod sursa(job #1658216)

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

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

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

class scanner {
public:
    inline scanner& operator >> (int &val)
    {
        while(!isdigit(buff[poz]))
            if(++poz==bmax) ff.read(buff, bmax), poz=0;
        val=0;
        while(isdigit(buff[poz]))
        {
            val=(val<<1)+(val<<3)+buff[poz]-'0';
            if(++poz==bmax) ff.read(buff, bmax), poz=0;
        }
        return *this;
    }
} fin;

bool bfs(int source, int dest)
{
    vector <int> :: iterator son;
    queue <int> q;
    int dad;
    viz=0;
    q.push(source);
    viz[source]=true;
    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])
            {
                viz[*son]=true;
                dady[*son]=dad;
                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 && f[*son][dest] < c[*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;
}

int main()
{
    ios_base::sync_with_stdio(false);
    int i, x, y, cap;
    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);
    ff.close();
    fout.close();
    return 0;
}