Cod sursa(job #2051086)

Utilizator UrsuDanUrsu Dan UrsuDan Data 28 octombrie 2017 15:23:36
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.51 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

const int N_MAX = 1010;
const int CAP_MAX = 110010;

vector < int > g[N_MAX];

int cap[N_MAX][N_MAX];
int flow[N_MAX][N_MAX];

int dad[N_MAX];

bool sour[N_MAX];
bool dest[N_MAX];


int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    int n, m;
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        scanf("%d%d%d", &x, &y, &c);
        sour[y] = true;
        dest[x] = true;
        g[x].push_back(y);
        g[y].push_back(x);
        cap[x][y] = c;
    }
    int source;
    for(int i = 1; i <= n; i++)
        if(sour[i] == false)
        {
            source = i;
            break;
        }
    int destination;
    for(int i = 1; i <= n; i++)
        if(dest[i] == false)
        {
            destination = i;
            for(int j = 0; j < g[i].size(); j++)
                dest[g[i][j]] = false;
            break;
        }
    bool ok = true;
    while(ok == true)
    {
        ok = false;
        queue < pair< int, int > > q;
        q.push({source, CAP_MAX});
        memset(dad, 0, sizeof(dad));
        while(!q.empty())
        {
            pair < int, int > node = q.front();
            q.pop();
            for(int i = 0; i < g[node.first].size(); i++)
            {
                int next = g[node.first][i];
                if(dad[next] == 0 && cap[node.first][next] - flow[node.first][next] > 0)
                {
                    dad[next] = node.first;
                    int mini = min(node.second, cap[node.first][next] - flow[node.first][next]);
                    q.push({next, mini});
                    if(dest[next] == false && cap[next][destination] - flow[next][destination] > 0)
                    {
                        ok = true;
                        mini = min(mini, cap[next][destination] - flow[next][destination]);
                        dad[destination] = next;
                        for(int i = destination; i != source; i = dad[i])
                        {
                            flow[dad[i]][i] += mini;
                            flow[i][dad[i]] -= mini;
                        }
                    }
                }

            }
        }
    }
    long long flowmax = 0;
    for(int i = 0; i < g[source].size(); i++)
        flowmax += flow[source][g[source][i]];
    printf("%lld\n", flowmax);
    return 0;
}