Cod sursa(job #2926042)

Utilizator ArseniuVictorStefanArseniu Victor Stefan ArseniuVictorStefan Data 16 octombrie 2022 19:28:26
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <stdio.h>
#include <queue>

#define NMAX 1000

#define INF 0x3f3f3f3f

int n, m;
short g[NMAX][NMAX];
int capacity[NMAX][NMAX];
short parent[NMAX];

int maxflow(int s, int t)
{
    for(int i = 0; i < n; i++)
        parent[i] = -1;

    std::queue<std::pair<int, int>> Q;
    Q.push(std::make_pair(s, INF));
    parent[s] = -2;
    while(!Q.empty())
    {
        int u = Q.front().first;
        int flow = Q.front().second;
        Q.pop();
        for(int i = 1; i <= g[u][0]; i++)
        {
            int v = g[u][i];
            if(parent[v] == -1 && capacity[u][v])
            {
                int new_flow = std::min(flow, capacity[u][v]);
                Q.push(std::make_pair(v, new_flow));
                parent[v] = u;

                if(v == t)
                    return new_flow;
            }
        }
    }

    return 0;
}

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

    scanf("%d %d", &n, &m);

    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            g[i][j] = capacity[i][j] = 0;

    for(int i = 0; i < m; i++)
    {
        int u, v, w;
        scanf("%d %d %d", &u, &v, &w);
        u--; v--;
        capacity[u][v] = w;
        capacity[v][u] = 0;
        g[u][++g[u][0]] = v;
        g[v][++g[v][0]] = u;
    }

    int flow = 0;
    int new_flow;
    while((new_flow = maxflow(0, n - 1)))
    {
        flow += new_flow;
        int cur = n - 1;
        while(cur != 0)
        {
            int prev = parent[cur];
            capacity[prev][cur] -= new_flow;
            capacity[cur][prev] += new_flow;
            cur = prev;
        }
    }

    printf("%d\n", flow);
}