Cod sursa(job #771306)

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

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

vector<int> bfs(int source, int dest) {
    queue<int> toBeProc;
    vector<int> path;    
    int parent[NMAX];   
    
    memset(parent, 0, sizeof(parent));
    
    toBeProc.push(source);
    parent[source] = -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 (el == dest) {
            break;        
        }                  
    }   
    if (parent[dest] == 0) {
        return path;
    }
    
    int child;
    while (dest != -1) {    
        path.push_back(dest);       
        dest = parent[dest];
    }
    
    return path;
}

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

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

void EdmondsKarp() {
    int cf;
    int s = 0;
    while (true) {
        vector<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;
}