Cod sursa(job #2288302)

Utilizator razviii237Uzum Razvan razviii237 Data 23 noiembrie 2018 08:45:10
Problema Flux maxim Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

const int maxn = 1005, maxm = 5005, inf = 0x3f3f3f3f;

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

int n, m, i, ans;
vector <int> gr[maxn];

int c[maxn][maxn], us[maxn][maxn]; // cost, used
int p[maxn]; bool is[maxn];
queue <int> q;

bool bfs()
{
    memset(is, false, sizeof(is));
    while(!q.empty()) {
        q.pop();
    }

    q.push(1);
    is[1] = true;

    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        if(x == n) { continue; }

        for(auto u : gr[x])
        {
            if(!(is[u] == true || us[x][u] == c[x][u])) {
                p[u] = x;
                q.push(u);
                is[u] = true;
            }
        }
    }
    return is[n];
}

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

    while(bfs())
    {
        for(auto u : gr[n])
        {
            if(us[u][n] == c[u][n] || is[u] == false) {
                continue;
            }
            p[n] = u;
            int minim = inf;
            for(int nod = p[n]; nod != 1; nod = p[nod]) {
                minim = min(minim, c[p[nod]][nod] - us[p[nod]][nod]);
            }
            for(int nod = p[n]; nod != 1; nod = p[nod]) {
                us[nod][p[nod]] -= minim;
                us[p[nod]][nod] += minim;
            }

            ans += minim;
        }
    }

    g << ans << '\n';

    f.close();
    g.close();
    return 0;
}