Cod sursa(job #2941142)

Utilizator cristia_razvanCristia Razvan cristia_razvan Data 17 noiembrie 2022 10:41:16
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define mp make_pair
#define dbg(x) cout << #x <<": " << x << "\n";
#define sz(x) ((int)x.size())

using ll = long long;

const string fn = "maxflow";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");

const int mxn = 1000;
const int oo = 2e9;

int n, m, S, D;

int flux;
int t[mxn + 5];
int c[mxn + 5][mxn + 5]; // cap    de pe muchie
int f[mxn + 5][mxn + 5]; // fluxul de pe muchie


vector<int> g[mxn + 5];

queue<int> q;

bool bfs(int s, int d)
{

    fill(t, t + n + 1, 0);

    q.push(s);
    t[s] = -1;
    while(!q.empty())
    {

        int nod = q.front();
        q.pop();
        for(auto i : g[nod])
            if(!t[i] && c[nod][i] > f[nod][i])
            {
                q.push(i);
                t[i] = nod;
            }

    }
    return (t[d] != 0);

}

int main()
{

    ios_base::sync_with_stdio(false);
    cin.tie();

    fin >> n >> m;

    S = 1;
    D = n;
    while(m--)
    {
        int x, y, cap;
        fin >> x >> y >> cap;
        c[x][y] = cap;
        g[x].pb(y);
        g[y].pb(x);
	}
	S = 1; D = n;


    while(bfs(S, D))
    {
        for(int i = 1; i <= n; ++i)
        {
            if(t[i] == -1 || c[i][D] <= f[i][D]) continue;
            int r = c[i][D] - f[i][D];
            for (int j = i; j != S && j > 0; j = t[j])
                r = min(r, c[t[j]][j] - f[t[j]][j]);
            if (r == 0) continue;
            f[i][D] += r;
            f[D][i] -= r;
            for (int j = i; j != S; j = t[j])
            {
                f[t[j]][j] += r;
                f[j][t[j]] -= r;
            }
            flux += r;
        }
    }
    fout << flux << '\n';


    return 0;
}