Cod sursa(job #771296)

Utilizator mi5humihai draghici mi5hu Data 25 iulie 2012 15:26:14
Problema Flux maxim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.83 kb
#include <stdio.h>
#include <vector>
#include <queue>
#include <limits>

#define NMAX 1002
#define MMAX 5002

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

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

int n;

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

vector< pair<int, int> > bfs(int source, int dest) {
    queue<int> toBeProc;
    vector< pair <int, int> > path;
    
    int parent[NMAX];
    bool processed[NMAX];    
    
    for (int i = 1; i <= n; i++) {
        processed[i] = false;
        parent[i] = 0;
    }
    
    toBeProc.push(source);
    processed[source] = true;     
    bool END = false;
    while (!toBeProc.empty()) {
        int el = toBeProc.front();
        toBeProc.pop();
        
        vector<int>::iterator it;
        for (it = edg[el].begin(); it != edg[el].end(); it++) {
            if (!processed[*it] && CapacRez(el, *it) > 0) {
                parent[*it] = el;
                processed[*it] = true;
                toBeProc.push(*it);
                
                if (*it == source) {
                    END = true;        
                    break;
                }   
            }             
        }
        if (END == true) {
            break;        
        }                  
    }   
    
    int child;
    while (parent[dest] != 0) {         
        child = dest;
        dest = parent[dest];
        path.push_back(make_pair(dest, child));  
    }
    
    return path;
}

int get_min(int &cf, vector< pair<int, int> > path) {
    cf = std::numeric_limits<int>::max();
    vector< pair<int, int> >::iterator it;
    for (it = path.begin(); it != path.end(); it++) {
        int x = (*it).first, y = (*it).second;
        if (cf > CapacRez(x, y)) {
            cf =  CapacRez(x, y);   
        }
    }     
}

void modify(int cf, vector< pair<int, int> > path) {
    vector< pair<int, int> >::iterator it;
    for (it = path.begin(); it != path.end(); it++) {
        int x = (*it).first;
        int y = (*it).second;
        
        Flux[x][y] += cf;
        Flux[y][x] = -Flux[x][y];
    }  
}

int EdmondsKarp() {
    int cf;
    int s = 0;
    while (true) {
        vector< pair<int, int> > path = bfs(1, n);
        if (path.empty()) {
            break;           
        }         
        get_min(cf, path);             
        modify(cf, path);        
        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;
}