Cod sursa(job #2467638)

Utilizator educationalLets Go educational Data 4 octombrie 2019 19:07:57
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
using namespace std;

#define MaxN 1000

queue<int> Q;
vector<int> L[MaxN + 1];
int c[MaxN + 1][MaxN + 1];
int f[MaxN + 1][MaxN + 1];
int t[MaxN + 1];
int N, M, flux;

bool BFS(int source)
{
    memset(t, 0, sizeof(t));
    t[source] = -42;
    Q.push(source);

    while(!Q.empty())
    {
        int node = Q.front();
        Q.pop();

        for(auto neighbour : L[node])
        if(!t[neighbour] && f[node][neighbour] < c[node][neighbour])
        {
            t[neighbour] = node;
            Q.push(neighbour);
        }
    }

    return (t[N] > 0);
}

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

    int i, x, y, cost, qnt;

    scanf("%d %d", &N, &M);
    for(i = 1; i <= M; i++)
    {
        scanf("%d %d %d", &x, &y, &cost);
        L[x].push_back(y);
        L[y].push_back(x);
        c[x][y] = cost;
    }

    while(BFS(1))
        for(auto node : L[N])
        if(t[node] && f[node][N] < c[node][N])
        {
            qnt = c[node][N] - f[node][N];
            for(x = node; t[x] > 0; x = t[x]) qnt = min(qnt, c[ t[x] ][x] - f[ t[x] ][x]);
            if(qnt == 0) continue;

            flux += qnt;
            f[node][N] += qnt;
            f[N][node] -= qnt;
            for(x = node; t[x] > 0; x = t[x])
            {
                f[ t[x] ][x] += qnt;
                f[x][ t[x] ] -= qnt;
            }
        }

    printf("%d\n", flux);



return 0;
}