Cod sursa(job #2532276)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 27 ianuarie 2020 17:45:31
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>

using namespace std;

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

const int Nmax = 1000, inf = 0x3f3f3f3f;

vector <int> g[Nmax + 5];
queue <int> q;
int n, m, node, flow;
int c[Nmax + 5][Nmax + 5], f[Nmax + 5][Nmax + 5], tt[Nmax + 5];
bool use[Nmax + 5];

void Read(){
    fin >> n >> m;
    for (int i = 1; i <= m; i++){
        int x, y, z;
        fin >> x >> y >> z;
        g[x].push_back(y);
        g[y].push_back(x);
        c[x][y] = z;
    }
}

int BFS(){
    memset(use, 0, sizeof use);
    memset(tt, 0, sizeof tt);
    while (!q.empty())
        q.pop();
    q.push(1);
    while (!q.empty()){
        node = q.front();
        q.pop();
        for (auto other : g[node]){
            if (c[node][other] - f[node][other] == 0 || use[other])
                continue;
            tt[other] = node;
            use[other] = 1;
            q.push(other);
        }
    }
    return use[n];
}

void Solve(){
    while (BFS()){
        for (int other : g[n]){
            tt[n] = other;
            if (c[other][n] - f[other][n] == 0 || !use[other])
                continue;
            int addmin = inf;
            for (int i = n; i != 1; i = tt[i])
                addmin = min(addmin, c[tt[i]][i] - f[tt[i]][i]);
            for (int i = n; i != 1; i = tt[i]){
                f[tt[i]][i] += addmin;
                f[i][tt[i]] -= addmin;
            }
        }
    }
}

void Print(){
    node = 1;
    for (auto other : g[node])
        flow += f[node][other];
    fout << flow << '\n';
}

int main(){
    Read();
    Solve();
    Print();
    return 0;
}