Cod sursa(job #1988642)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 3 iunie 2017 22:23:20
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

vector<int> v[1005];
int c[1005][1005], f[1005][1005], n, m, vis[1005], l[1005];

int bfs()
{
    queue<int> q;
    q.push(1);
    vis[1] = 1;
    while(!q.empty() && !vis[n]){
        int x = q.front();
        q.pop();
        for (unsigned i = 0; i < v[x].size(); ++i)
            if(!vis[v[x][i]]){
                if(f[x][v[x][i]] < c[x][v[x][i]]){
                    vis[v[x][i]] = x;
                    q.push(v[x][i]);
                }else if (f[v[x][i]][x] > 0){
                    vis[v[x][i]] = -x;
                    q.push(i);
                }
            }
    }
    return !vis[n];
}

int abs(int x)
{
    return x >= 0 ? x : -x;
}

int main()
{
    ifstream fin ("maxflow.in");
    ofstream fout ("maxflow.out");
    fin >> n >> m;
    while(m--){
        int x, y, z;
        fin >> x >> y >> z;
        if(c[x][y] == 0)
            v[x].push_back(y);
        if(c[y][x] == 0)
            v[y].push_back(x);
        c[x][y] = z;
    }
    do{
        for (int i = 0; i < 1005; ++i)
            vis[i] = 0;
        if(bfs())
            break;
        int lg = 0;
        l[0] = n;
        int a, b, val;
        a = b = 1000000000;
        while(l[lg] != 1){
            ++lg;
            l[lg] = abs(vis[l[lg-1]]);
            if(vis[l[lg-1]] > 0)
                a = min(a, c[l[lg]][l[lg-1]] - f[l[lg]][l[lg-1]]);
            else if (vis[l[lg-1]] < 0)
                b = min(b, f[l[lg-1]][l[lg]]);
        }
        val = min(a, b);
        for (int i = lg; i; --i)
            if(vis[l[i-1]] > 0)
                f[l[i]][l[i-1]] += val;
            else f[l[i-1]][l[i]] -= val;
    }while(1);
    int fm = 0;
    for (int i = 1; i <= n; ++i)
        fm += f[i][n];
    fout << fm << "\n";
    fin.close();
    fout.close();
    return 0;
}