Cod sursa(job #2587857)

Utilizator RazvanPanaiteRazvan Panaite RazvanPanaite Data 23 martie 2020 17:30:40
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.48 kb
#include <bits/stdc++.h>
#define pb push_back

using namespace std;

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

void debug_out() { cerr << '\n'; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << H; debug_out(T...);}
#define dbg(...) cerr << #__VA_ARGS__ << " ->", debug_out(__VA_ARGS__)
#define dbg_v(x, n) do{cerr<<#x"[]: ";for(int _=0;_<n;++_)cerr<<x[_]<<" ";cerr<<'\n';}while(0)
#define dbg_ok cerr<<"OK!\n"

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

const int DMAX = 1e5+10;

class maxFlow {
  private:
    int n,start,dest;
    vector<vector<int>> V;
    vector<vector<int>> cap;

    bool bfs(vector<bool>& uz, vector<int>& tata) {
        fill(uz.begin(), uz.end(), false);
        uz[start] = true;

        queue<int> q; q.push(start);
        while (!q.empty()) {
            int node = q.front(); q.pop();
            for (auto& it : V[node])
                if (!uz[it] && cap[node][it]) {
                    uz[it] = true;
                    tata[it] = node;
                    if (it != dest)
                        q.push(it);
                }
        }
        return uz[dest];
    }

  public:
    maxFlow(int n,int start,int dest){
        this->n=n;
        this->start=start;
        this->dest=dest;
        V.resize(n+1);
        cap.resize(n+1,vector <int> (n+1));
    }

    void addEdge(int x, int y, int z) {
        V[x].push_back(y);
        V[y].push_back(x);
        cap[x][y]=z;
    }

    int getMaxFlow() {
        vector<bool> uz(n + 1);
        vector<int> tata(n + 1);

        int ans = 0;
        while(bfs(uz, tata))
            for(int it : V[dest])
                if(uz[it] && cap[it][dest]) {
                    int flow = 1e9;
                    tata[dest] = it;

                    for (int i = dest; i != start; i = tata[i])
                        flow = min(flow, cap[tata[i]][i]);

                    for (int i = dest; i != start; i = tata[i]) {
                        cap[tata[i]][i] -= flow;
                        cap[i][tata[i]] += flow;
                    }
                    ans += flow;
                }
        return ans;
    }
};

int V[DMAX];

int n,m;

int main(){
    int t,i,j;
    int x,y,z;

    fin>>n>>m;
    maxFlow flux(n,1,n);
    while(m--){
        fin>>x>>y>>z;
        flux.addEdge(x,y,z);
    }
    fout<<flux.getMaxFlow()<<'\n';
    return 0;
}