Cod sursa(job #2586622)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 21 martie 2020 11:57:10
Problema Algola Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.6 kb
#include <bits/stdc++.h>
using namespace std;

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

class FlowNetwork {
  private:
    int n, s, t;
    vector<vector<int>> ad, cap, cpy;

    bool bfs(vector<bool>& vis, vector<int>& father) {
        fill(vis.begin(), vis.end(), false);
        vis[s] = true;
        queue<int> q; q.push(s);
        while (!q.empty()) {
            int node = q.front(); q.pop();
            for (int nghb : ad[node])
                if (!vis[nghb] && cap[node][nghb]) {
                    vis[nghb] = true;
                    father[nghb] = node;
                    if (nghb != t)
                        q.push(nghb);
                }
        }
        return vis[t];
    }

  public:
    FlowNetwork(int n, int s, int t) :
        n(n), s(s), t(t), ad(n + 1),
        cap(n + 1, vector<int>(n + 1)) { }

    void addDirEdge(int x, int y, int z) {
        ad[x].push_back(y);
        ad[y].push_back(x);
        cap[x][y] = z;
    }

    void addUndirEdge(int x, int y, int z) {
        ad[x].push_back(y);
        ad[y].push_back(x);
        cap[x][y] = cap[y][x] = z;
    }

    void backup() {
        cpy = cap;
    }

    void maxFlow() {
        vector<bool> vis(n + 1);
        vector<int> father(n + 1);
        while (bfs(vis, father))
            for (int nghb : ad[t])
                if (vis[nghb] && cap[nghb][t]) {
                    int flow = 1e9;
                    father[t] = nghb;
                    for (int i = t; i != s; i = father[i])
                        flow = min(flow, cap[father[i]][i]);
                    for (int i = t; i != s; i = father[i]) {
                        cap[father[i]][i] -= flow;
                        cap[i][father[i]] += flow;
                    }
                }
    }

    int flowIterations() {
        int cnt = 0;
        while (true) {
            cnt++;
            maxFlow();
            bool done = true;
            for (int j = 1; j <= n; j++)
                if (cap[0][j]) {
                    done = false;
                    break;
                }
            if (done)
                break;
            for (int i = 1; i <= n; i++)
                copy(cpy[i].begin(), cpy[i].end(), cap[i].begin());
        }
        return cnt;
    }
};

int main() {
    int n, m; fin >> n >> m;
    FlowNetwork graph(n, 0, 1);

    for (int i = 1; i <= n; i++) {
        int x; fin >> x;
        graph.addDirEdge(0, i, x);
    }
    for (int i = 0; i < m; i++) {
        int x, y, z; fin >> x >> y >> z;
        graph.addUndirEdge(x, y, z);
    }

    graph.backup();
    fout << graph.flowIterations() << '\n';

    fout.close();
    return 0;
}