Cod sursa(job #1515508)

Utilizator diana97Diana Ghinea diana97 Data 1 noiembrie 2015 18:23:23
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f ("maxflow.in");
ofstream g ("maxflow.out");

const int INF = (1 << 30);
const int NMAX = 1000 + 1;

int n, m;

int sursa, destinatie;

int superior[NMAX];
bool vizitat[NMAX];

int capacitate[NMAX][NMAX], flux[NMAX][NMAX];
vector <int> graf[NMAX];

void citeste() {
    int nod1, nod2, c;

    f >> n >> m;
    for (int i = 1; i <= m; i++) {
        f >> nod1 >> nod2 >> c;

        graf[nod1].push_back(nod2);
        graf[nod2].push_back(nod1);

        capacitate[nod1][nod2] += c;
    }
}

bool BFS() {
    int nod, nr_fii, fiu;
    queue <int> Q;

    for (int i = 1; i <= n; i++)
        vizitat[i] = false;

    Q.push(sursa);
    vizitat[sursa] = true;

    while (!Q.empty()) {
        nod = Q.front();
        //cout << nod << ' ';
        Q.pop();

        if (nod == destinatie)
            break;

        nr_fii = graf[nod].size();
        for (int i = 0; i < nr_fii; i++) {
            fiu = graf[nod][i];
            if (!vizitat[fiu] && flux[nod][fiu] < capacitate[nod][fiu]) {
                vizitat[fiu] = true;
                Q.push(fiu);
                superior[fiu] = nod;
            }
        }
    }
    //cout << endl;

    return vizitat[destinatie];
}


int flux_maxim() {
    int nod, ant, minim, sol = 0;
    int nr_fii;

    while (BFS()) {
        int nr_fii = graf[destinatie].size();
        for (int i = 0; i < nr_fii; i++) {
            nod = graf[destinatie][i];
            if (!vizitat[nod]) continue;

            superior[destinatie] = nod;
            nod = destinatie;
            minim = INF;

            while (nod != sursa) {
                ant = superior[nod];
                minim = min(minim, capacitate[ant][nod] - flux[ant][nod]);
                nod = ant;
            }

            nod = destinatie;

            while (nod != sursa) {
                ant = superior[nod];
                flux[ant][nod] += minim;
                flux[nod][ant] -= minim;
                nod = ant;
            }

            sol += minim;
        }
    }

    return sol;
}

int main() {
    citeste();
    sursa = 1;
    destinatie = n;
    g << flux_maxim() << '\n';
    return 0;
}