Cod sursa(job #771313)

Utilizator mi5humihai draghici mi5hu Data 25 iulie 2012 16:32:15
Problema Flux maxim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.27 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];

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

int n;

int CapacRez(int x, int y) {
    return (Capac[x][y] - Flux[x][y]);
}

void bfs() {
    queue<int> toBeProc; 
    
    memset(parent, 0, (n + 2) * 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++) {
            if (parent[*it] == 0 && CapacRez(el, *it) > 0) {
                parent[*it] = el;
                toBeProc.push(*it);   
                if (*it == n) {
                   break;        
                }
            }     
        }
        if (toBeProc.back() == n) {
            break;        
        }                  
    }   
}

int get_min() {
    int cf = std::numeric_limits<int>::max();
    vector<int>::iterator it;
    
    int dest = n;
    while (parent[dest] != -1){
        if (cf > CapacRez(parent[dest], dest)) {
            cf =  CapacRez(parent[dest], dest);   
        }
        dest = parent[dest];
    }   
    return cf; 
}

void modify(int cf) {
    vector<int>::iterator it;
    
    int dest = n;
    while (parent[dest] != -1){
        Flux[parent[dest]][dest] += cf;
        Flux[dest][parent[dest]] = -Flux[parent[dest]][dest];
        dest = parent[dest];
    }  
}

void EdmondsKarp() {
    int cf;
    int s = 0;
    while (true) {
        bfs();
        if (parent[n] == 0) {
            break;           
        }       
        
        cf = get_min();             
        modify(cf);        
        s += cf;
    }    
    printf("%d", s); 
}

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);
        Capac[s][d] = c;
    }      
}

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