Cod sursa(job #3003595)

Utilizator PingStrpewpewpac PingStr Data 15 martie 2023 20:07:28
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int N = 1e3+2, INF = 2e7;
int parent[N];
int cap[N][N];
vector<int> gr[N];


bool bfs(int s, int t)
{
    memset(parent, 0, sizeof(parent));
    queue<int> q;
    parent[s] = 1;
    q.push(s);
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        for (auto i: gr[nod])
        {
            if (parent[i] == 0 && cap[nod][i] > 0)
            {
                q.push(i);
                parent[i] = nod;
                if (i == t)
                    return true;
            }
        }
    }

    return false;
}

int maxflow(int s, int t)
{
    int flow = 0;
    while (bfs(s, t))
    {
        int minflow = INF;
        for (auto i: gr[t])
        {
            if (parent[i] == 0) continue;

            int nod = t;
            while (nod != s)
            {
                minflow = min(minflow, cap[parent[nod]][nod]);
                nod = parent[nod];
            }
            nod = t;
            while (nod != s)
            {
                cap[parent[nod]][nod] -= minflow;
                cap[nod][parent[nod]] += minflow;
                nod = parent[nod];
            }
            flow += minflow;
        }
    }
    return flow;
}

int main()
{
    int n, m, x, y, z;
    fin>>n>>m;
    for (int i = 1; i <= m; i++)
    {
        fin>>x>>y>>z;
        gr[x].push_back(y);
        gr[y].push_back(x);
        cap[x][y] = z;
    }
    fout<<maxflow(1, n);
}