Cod sursa(job #2417689)

Utilizator mihai.alphamihai craciun mihai.alpha Data 30 aprilie 2019 20:39:53
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m;

const int maxn = 1e3 + 5;

#define fi first
#define se second

vector <int> v[maxn];
int flx[maxn][maxn];
int cap[maxn][maxn];

bool viz[maxn];
int pre[maxn];

inline bool BFS()  {
    queue <int> q;
    memset(viz, 0, sizeof(viz));
    viz[1] = 1;
    q.push(1);
    while(!q.empty())  {
        int nod = q.front();
        q.pop();
        if(nod != n)  {
            for(auto &x : v[nod])
                if(viz[x] == 0 && flx[nod][x] != cap[nod][x])  {
                    viz[x] = 1;
                    pre[x] = nod;
                    q.push(x);
                }
        }
    }
    return viz[n];
}

int main()  {
    fin >> n >> m;
    for(int i = 1;i <= m;i++)  {
        int x, y, f;
        fin >> x >> y >> f;
        v[x].push_back(y);
        v[y].push_back(x);
        cap[x][y] += f;
    }
    int Tot = 0;
    while(BFS())  {
        for(auto x : v[n])  {
            if(viz[x] && flx[x][n] != cap[x][n])  {
                pre[n] = x;
                int ss = n;
                int ans = INT_MAX;
                while(ss != 1)  {
                    ans = min(ans, cap[pre[ss]][ss] - flx[pre[ss]][ss]);
                    ss = pre[ss];
                }
                if(ans != 0)  {
                    Tot += ans;
                    int ss = n;
                    while(ss != 1)  {
                        flx[pre[ss]][ss] += ans;
                        flx[ss][pre[ss]] -= ans;
                        ss = pre[ss];
                    }
                }
            }
        }
    }
    fout << Tot;
    fin.close();
    fout.close();
    return 0;
}