Cod sursa(job #771513)

Utilizator mi5humihai draghici mi5hu Data 26 iulie 2012 10:49:30
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.65 kb
#include <stdio.h>
#include <vector>
#include <queue>
#include <limits>
#include <cstring>

#define NMAX 1002
#define MMAX 5002

using namespace std;
vector<int> edg[NMAX];
vector<int> terminal;

int Capac[NMAX][NMAX];
int parent[NMAX];  

int n;

bool bfs() {
    queue<int> toBeProc;         
    memset(parent, 0, NMAX * sizeof(int));
    
    toBeProc.push(1);
    parent[1] = -1;  
    
    while (!toBeProc.empty()) {
        int el = toBeProc.front();
        toBeProc.pop();
        
        vector<int>::iterator it;
        for (it = edg[el].begin(); it != edg[el].end(); it++) {
            int next = *it;
            if (parent[next] == 0 && Capac[el][next] > 0) {
                parent[next] = el;
                toBeProc.push(next);   
            }     
        }   
           
    }
    return (parent[n] != 0);
}

int get_min(int dest) {
    int cf = Capac[dest][n];
    
    while (parent[dest] != -1){
        int cr =  Capac[parent[dest]][dest];
        if (cf > cr) {
            cf = cr;   
            if (cf <= 0) {
                return cf;
            }
        }
        dest = parent[dest];
    }   
    return cf; 
}

void modify(int cf, int dest) {    
    Capac[dest][n] -= cf;
    Capac[n][dest] += cf;
    if (Capac[n][dest] <= cf && Capac[n][dest] > 0) {
        edg[n].push_back(dest);                              
    } 
     
    while (parent[dest] != -1){
        Capac[parent[dest]][dest] -= cf;
        Capac[dest][parent[dest]] += cf;
        if (Capac[dest][parent[dest]] <= cf && Capac[dest][parent[dest]] > 0) {
            edg[dest].push_back(parent[dest]);                              
        }
        dest = parent[dest];
    }  
}

void EdmondsKarp() {
    int cf;
    int sum = 0;
    while (bfs()) {           
        vector<int>::iterator it;
        for (it = terminal.begin(); it != terminal.end(); it++) {
            int el = *it;
            if (Capac[el][n] > 0) {
                cf = get_min(el);             
                if (cf > 0) {
                    modify(cf, el);        
                    sum += cf;
                }
            }
        }
    }    
    printf("%d", sum); 
}

void read_() {
    int m, s, d, c;
    
    scanf("%d%d", &n, &m);
    for (int i = 0; i < m; i++) {
        scanf("%d%d%d", &s, &d, &c);
        edg[s].push_back(d);
        if (d == n) {
            terminal.push_back(s);   
        }
        Capac[s][d] = c;
    }      
}

int main() {
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    
    read_();
    EdmondsKarp();  
    
    return 0;
}