Cod sursa(job #2014458)

Utilizator MaarcellKurt Godel Maarcell Data 23 august 2017 18:18:26
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.76 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cmath>
#include <cstring>
#include <ctime>
#include <unordered_map>
#include <iomanip>
using namespace std;

#define fi first
#define se second
#define pb push_back
#define all(v) (v).begin(),(v).end()

typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef pair<int,int> pii;

struct MaxFlow{
    vector<vi> c,f,g;
    vi tt;
    int s,t,N;

    MaxFlow(int N, int s, int t){
        this->N = N, this->s = s, this->t = t;

        c.resize(N),f.resize(N),g.resize(N);
        for (int i=0; i<N; i++)
            c[i].resize(N),f[i].resize(N);

    }

    int getmaxflow(){
        int res=0;
        for (int i=0; i<N; i++)
            fill(all(f[i]),0);

        while (bfs()){
            int nod;
            for (nod=0; nod<N; nod++){
                if (c[nod][t]-f[nod][t]==0 || tt[nod]==-1) continue;

                tt[t]=nod;
                int cr,fmin=(1<<30);
                for (cr=t; cr!=s; cr=tt[cr])
                    fmin=min(fmin,c[tt[cr]][cr]-f[tt[cr]][cr]);

                res+=fmin;

                for (cr=t; cr!=s; cr=tt[cr]){
                    f[tt[cr]][cr]+=fmin;
                    f[cr][tt[cr]]-=fmin;
                }
            }
        }

        return res;
    }

    void add_edge(int from, int to, int cap){
        g[from].pb(to);
        //Remove if needed
        g[to].pb(from);
        c[from][to]=cap;
    }

    void print(){
        cout << N << "\n";
        for (int i=0; i<N; i++, cout << "\n")
            for (int j=0; j<N; j++)
                cout << c[i][j] << " ";
    }
    bool bfs(){
        tt.clear(),tt.resize(N,-1);
        int *q = new int[N+10],K=0,i;
        bool *v = new bool[N+10];

        for (i=0; i<N; i++) v[i]=0;

        q[K++]=s; v[s]=1;
        bool ok=0;
        for (i=0; i<K; i++){
            int nod = q[i];

            for (int nxt : g[nod]){
                if (c[nod][nxt]-f[nod][nxt]>0 && !v[nxt]){
                    if (nxt==t){
                        ok=1;
                        continue;
                    }

                    tt[nxt]=nod;
                    q[K++]=nxt;
                    v[nxt]=1;
                }
            }
        }
        return ok;
    }
};

int N,M;

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
	ifstream fin("maxflow.in");
	ofstream fout("maxflow.out");
    fin >> N >> M;

    int i;
    MaxFlow mxf(N,0,N-1);
    for (i=1; i<=M; i++){
        int x,y,c;
        fin >> x >> y >> c;
        x--,y--;
        mxf.add_edge(x,y,c);
    }

    fout << mxf.getmaxflow();
    return 0;
}