Cod sursa(job #2554097)

Utilizator iptonchevIvan Tonchev iptonchev Data 22 februarie 2020 16:28:20
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.44 kb
#include<fstream>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;

struct Edge {
    int to, c, revInd;
};

const int MAX_N = 1000;
const int INF = 110069;

vector<Edge> nbrs[MAX_N];
int level[MAX_N];
int firstE[MAX_N];

int n, m;
int s, t;

void bfs() {
    for(int i = 0; i < n; ++i) {
        level[i] = -1;
        firstE[i] = 0;
    }

    queue<int> q;
    q.push(s);
    level[s] = 0;

    while(!q.empty()) {
        int curr = q.front();
        q.pop();

        for(int i = 0; i < nbrs[curr].size(); ++i) {
            if(nbrs[curr][i].c == 0) {
                continue;
            }

            int nextV = nbrs[curr][i].to;

            if(level[nextV] == -1) {
                q.push(nextV);
                level[nextV] = level[curr] + 1;
            }
        }
    }
}

int dfs(int curr, int flow) {
    if(flow == 0) {
        return 0;
    }

    if(curr == t) {
        return flow;
    }

    int res = 0;

    for(int &i = firstE[curr]; i < nbrs[curr].size(); ++i) {
        int nextV = nbrs[curr][i].to;

        if(nbrs[curr][i].c == 0 || level[nextV] <= level[curr]) {
            continue;
        }

        int currRes = dfs(nextV, min(flow, nbrs[curr][i].c));
        int twinEdgeInd = nbrs[curr][i].revInd;
        nbrs[curr][i].c -= currRes;
        nbrs[nextV][twinEdgeInd].c += currRes;

        res += currRes;

        flow -= currRes;
        if(flow == 0) {
            break;
        }
    }

    return res;
}

int main() {
    #define cout myfileOut
    ofstream myfileOut;
    myfileOut.open ("maxflow.out");

    #define cin myFileIn
    ifstream myFileIn;
    myFileIn.open ("maxflow.in");

    ///ios_base::sync_with_stdio(false);
    ///cin.tie(0);

    cin >> n >> m;
    /// cin >> s >> t;

    --s;
    --t;
    /// idiot*
    /// * Blago, ne az

    s = 0;
    t = n - 1;

    for(int i = 0; i < m; ++i) {
        int from, to, c;
        cin >> from >> to >> c;

        --from;
        --to;

        int frontRevInd = nbrs[to].size();
        int backRevInd = nbrs[from].size();

        nbrs[from].push_back({to, c, frontRevInd});
        nbrs[to].push_back({from, 0, backRevInd});
    }

    int res = 0;

    while(true) {
        bfs();

        if(level[t] == -1) {
            break;
        }

        res += dfs(s, INF);
    }

    cout << res << endl;

    return 0;
}