Cod sursa(job #1502760)

Utilizator stefanzzzStefan Popa stefanzzz Data 14 octombrie 2015 23:37:18
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <stdio.h>
#include <vector>
#include <queue>
#include <string.h>
#define MAXN 1005
#define MIN(a, b) (((a) < (b))?(a):(b))
using namespace std;

int x, y, c;
int n, m, fx[MAXN][MAXN], cap[MAXN][MAXN], bk[MAXN];
vector<int> G[MAXN];

bool BFS() {
    queue<int> q;
    memset(bk, 0, sizeof(bk));

    bk[1] = -1;
    q.push(1);
    while(!q.empty()) {
        int x = q.front();
        q.pop();

        for(auto y: G[x])
            if(!bk[y] && fx[x][y] < cap[x][y]) {
                bk[y] = x;
                q.push(y);
            }
    }

    return bk[n];
}

int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);

    scanf("%d %d", &n, &m);
    for(int i = 1; i <= m; i++) {
        scanf("%d %d %d", &x, &y, &c);
        cap[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    while(BFS()) {
        for(auto x: G[n]) {
            int flow = cap[x][n] - fx[x][n];
            int y = x;

            if(!flow || !bk[x]) continue;
            while(y != 1 && flow) {
                flow = MIN(flow, cap[bk[y]][y] - fx[bk[y]][y]);
                y = bk[y];
            }

            if(!flow) continue;
            fx[x][n] += flow;
            fx[n][x] -= flow;
            y = x;
            while(y != 1) {
                fx[bk[y]][y] += flow;
                fx[y][bk[y]] -= flow;
                y = bk[y];
            }
        }
    }

    int sol = 0;
    for(auto x: G[1])
        sol += fx[1][x];
    printf("%d\n", sol);

    return 0;
}