Cod sursa(job #999635)

Utilizator radustn92Radu Stancu radustn92 Data 21 septembrie 2013 02:55:04
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <cstdio>
#include <bitset>
#include <vector>
#include <algorithm>
#include <queue>
#include <Cstring>
#define pb push_back
#define pii pair <int, int>
#define mp make_pair
#define x first
#define y second
#define NMAX 1005
#define INF 1000000000
using namespace std;
int n, m, F[NMAX][NMAX], C[NMAX][NMAX], dad[NMAX], D[NMAX], flow;
int source, dest;
vector <int> G[NMAX];
priority_queue <pii> Q;

int BF()
{
    memset(D, 0, sizeof(D));
    Q.push(mp(INF, source)); D[source] = INF; 
    
    int j, node, x, cost;
    while (!Q.empty())
    {
        node = Q.top().y; cost = Q.top().x;
        Q.pop();
        if (D[node] > cost || node == dest)
            continue ;
        
        for (j = 0; j < (int)G[node].size(); j++)
        {
            x = G[node][j];
            if (D[x] < min(cost, C[node][x] - F[node][x]))
            {
                D[x] = min(cost, C[node][x] - F[node][x]); dad[x] = node;
                Q.push(mp(D[x], x));
            }
        }
    }
    
    return D[dest];
}

void max_flow()
{
    int node, fmin;
    while (BF())
    {
        fmin = INF;
        for (node = dest; node != source; node = dad[node])
            fmin = min(fmin, C[dad[node]][node] - F[dad[node]][node]);
        
        for (node = dest; node != source; node = dad[node])
        {
            F[dad[node]][node] += fmin;
            F[node][dad[node]] -= fmin;
        }
        
        flow += fmin;
    }
}

int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    scanf("%d%d", &n, &m);
    int i, x, y, z;
    for (i = 1; i <= m; i++)
    {
        scanf("%d%d%d", &x, &y, &z);
        G[x].pb(y); C[x][y] = z;
        G[y].pb(x);
    }
    
    source = 1; dest = n;
    max_flow();
    printf("%d\n", flow);
    return 0;
}