Cod sursa(job #1312211)

Utilizator thesvcoolmanLucian Bicsi thesvcoolman Data 8 ianuarie 2015 23:36:57
Problema Flux maxim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.65 kb
#include<fstream>
#include<vector>
#include<deque>
#define MAXN 1001
#define INF 125000

using namespace std;

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

int G[MAXN][MAXN];
vector<int> L[MAXN];
int n, m, source, destination;

vector<int> PATH;
vector<bool> VIZ;
vector<int> PARENT;

void afis(vector<int> &v) {
    for(int i=0; i<v.size(); i++) {
        fout<<v[i]<<" ";
    }fout<<endl;
}

void read() {
    fin>>n>>m;
    int a, b;
    VIZ.resize(n+1, false);
    PARENT.resize(n+1, 0);

    source = 1;
    destination = n;

    for(int i=1; i<=m; i++) {
        fin>>a>>b;
        fin>>G[a][b];
        L[a].push_back(b);
        L[b].push_back(a);
    }

}

bool done;
void getPath (int s, int d) {
    VIZ[s] = true;
    PATH.push_back(s);

    if(s == d) {
        done = true;
        return;
    }

    for(int i=0; i<L[s].size(); i++) {
        if(G[s][L[s][i]] and !VIZ[L[s][i]]) {
            getPath(L[s][i], d);
            if(done) return;
        }
    }
    PATH.pop_back();
}

void dfs(int s) {
    VIZ[s] = true;
    for(int i=0; i<L[s].size(); i++) {
        if(G[s][L[s][i]] and !VIZ[L[s][i]]) {
            PARENT[L[s][i]] = s;
            dfs(L[s][i]);
        }
    }
}

void res() {
    for(int i=0; i<L[destination].size(); i++) {

        int node = L[destination][i];
        int MIN=INF;
        //afis(PARENT);
        while(PARENT[node]) {
            MIN = min (MIN, G[PARENT[node]][node]);
            node = PARENT[node];
        }

        node = L[destination][i];

        while(PARENT[node]) {
            G[PARENT[node]][node] -= MIN;
            G[node][PARENT[node]] += MIN;
            node = PARENT[node];
        }
    }
}

void resGraph() {
    int MIN = G[PATH[0]][PATH[1]];
    for(int i=2; i<PATH.size(); i++) {
        MIN = min(MIN, G[PATH[i-1]][PATH[i]]);
    }
    for(int i=1; i<PATH.size(); i++) {
        G[PATH[i-1]][PATH[i]] -= MIN;
        G[PATH[i]][PATH[i-1]] += MIN;
    }
}

int main() {
    read();
    /*
    getPath(source, destination);
    while(done) {
        resGraph();
        done = false;
        for(int i=1; i<=n; i++) {
            VIZ[i] = false;
        }
        //afis(PATH);
        PATH.clear();
        getPath(source, destination);
    }*/

    dfs(source);
    while(VIZ[destination]) {
        res();
        for(int i=1; i<=n; i++) {
            VIZ[i] = false;
            PARENT[i] = 0;
        }
        dfs(source);
    }

    int flux = 0;
    for(int i=0; i<L[source].size(); i++) {
        flux +=G[L[source][i]][source];
    }
    fout<<flux;

    return 0;
}