Cod sursa(job #2603884)

Utilizator TheNextGenerationAyy LMAO TheNextGeneration Data 21 aprilie 2020 10:08:04
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int N = 1005;
int Cap[N][N],from[N];
bool viz[N];
vector<int> v[N];
bool BFS(int sink)
{
    queue<int> q;
    q.push(1);
    for (int i = 1; i<=sink; i++)
        viz[i] = 0;
    while (!q.empty())
    {
        int now = q.front();
        viz[now] = 1;
        q.pop();
        if (now == sink)
            continue;
        for (auto it: v[now])
            if (Cap[now][it]>0 && !viz[it])
            {
                viz[it] = 1;
                from[it] = now;
                q.push(it);
            }
    }
    return viz[sink];
}
int main()
{
    int n,m;
    in >> n >> m;
    for (int i = 1; i<=m; i++)
    {
        int x,y,c;
        in >> x >> y >> c;
        v[x].push_back(y);
        v[y].push_back(x);
        Cap[x][y]+=c;
    }
    int ans = 0;
    while(BFS(n))
    {
        for (auto last: v[n])
        {
            if (from[last] && Cap[last][n]>0)
            {
                int flowmin = INT_MAX;
                from[n] = last;
                for (int i = n; i!=1; i = from[i])
                    flowmin = min(flowmin,Cap[from[i]][i]);
                if (flowmin)
                {
                    ans+=flowmin;
                    for (int i = n; i!=1; i = from[i])
                    {
                        Cap[from[i]][i]-=flowmin;
                        Cap[i][from[i]]+=flowmin;
                    }
                }
            }
        }
    }
    out << ans;
}