Cod sursa(job #714945)

Utilizator PetcuIoanPetcu Ioan Vlad PetcuIoan Data 16 martie 2012 12:50:36
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include<stdio.h>
#include<assert.h>

#include<queue>
#include<vector>
#include<algorithm>

using namespace std;

const int knmax = 1024, ko9000 = 2000000000;
int sol, verts, edges, source = 1, destination, vis[knmax], father[knmax], cost[knmax][knmax], flow[knmax][knmax];

void read(){
    assert(freopen("maxflow.in","r",stdin)!=NULL);
    scanf("%d%d",&verts,&edges);
    destination = verts;
    int i, aux_x, aux_y, aux_cost;
    for(i = 1; i <= edges; ++i){
        scanf("%d%d%d",&aux_x,&aux_y,&aux_cost);
        cost[aux_x][aux_y] = aux_cost;
    }
}

void init(){
    for(int i = 1; i <= verts; ++i)
        vis[i] = 0;
}

int bfs(){
    init();
    queue<int> q;
    q.push(source);
    vis[source] = 1;
    while(!q.empty()){
        int node = q.front();
        q.pop();

        for(int i = 1; i <= verts; ++i)
            if(!vis[i] && cost[node][i] > flow[node][i]){
                father[i] = node;
                vis[i] = 1;
                q.push(i);

                if (i == destination) return 1;
            }
    }
    return 0;
}

void solve(){
    int c_flow, j;
    while(bfs()){
        for(j = 1; j < destination; ++j)
        if(flow[j][destination] < cost[j][destination] && vis[j]){
            c_flow = cost[j][destination] - flow[j][destination];
            for(int i = j; i != source; i = father[i])
                c_flow = min(c_flow,cost[father[i]][i] - flow[father[i]][i]);
            sol += c_flow;

            flow[j][destination] += c_flow;
            flow[destination][j] -= c_flow;
            for(int i = j; i != source; i = father[i]){
                flow[i][father[i]] -= c_flow;
                flow[father[i]][i] += c_flow;
            }
        }
    }
}

void write(){
    assert(freopen("maxflow.out","w",stdout)!=NULL);
    printf("%d",sol);
}

int main(){
    read();
    solve();
    write();
    return 0;
}