Cod sursa(job #2361029)

Utilizator lupulescu2001Lupulescu Vlad lupulescu2001 Data 2 martie 2019 12:28:30
Problema Algola Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>

using namespace std;

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

const int oo = 2000000000;
const int last = 5005;
int n, m;
vector<int> g[last + 5];
vector<pair<int, int>> a[55];
int c[last + 5][last + 5];
int total, use[last + 5], tt[last + 5];
int fmax, time;

void Add(int x, int y, int cap) {
    g[x].push_back(y);
    g[y].push_back(x);
    c[x][y] = cap;
}

void Read() {
    fin >> n >> m;
    for (int i = 1; i <= n; i++) {
        int x;
        fin >> x;
        Add(0, i, x);
        total += x;
    }
    Add(1, last, oo);
    for (int i = 1; i <= m; i++) {
        int x, y, cap;
        fin >> x >> y >> cap;
        a[x].push_back({y, cap});
        a[y].push_back({x, cap});
    }
}

int BFS() {
    memset(use, 0, sizeof(use));
    queue<int> q;
    q.push(0);
    use[0] = 1;
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        if (x == last)
            continue;
        for (auto i : g[x])
            if (use[i] == 0 && c[x][i]) {
                use[i] = 1;
                tt[i] = x;
                q.push(i);
            }
    }
    return use[last];
}

void GetFlow() {
    while (BFS()) {
        for (auto i : g[last])
            if (use[i] == 1 && c[i][last]) {
                tt[last] = i;
                int fmin = oo;
                for (int j = last; j; j = tt[j])
                    fmin = min(fmin, c[tt[j]][j]);
                for (int j = last; j; j = tt[j]) {
                    c[tt[j]][j] -= fmin;
                    c[j][tt[j]] += fmin;
                }
                fmax += fmin;
            }
    }
}

void Solve() {
    GetFlow();
    while (fmax < total) {
        time++;
        for (int i = 1; i <= n; i++) {
            Add((time - 1) * n + i, time * n + i, oo);
            for (auto j : a[i])
                Add((time - 1) * n + i, time * n + j.first, j.second);
        }
        Add(time * n + 1, last, oo);
        GetFlow();
    }
}

void Print() {
    fout << time << '\n';
}

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