Cod sursa(job #2325235)

Utilizator andreicoman299Coman Andrei andreicoman299 Data 22 ianuarie 2019 12:16:35
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.36 kb
#include <bits/stdc++.h>
#define MAXN 30000

struct Edge{int x, y, c;};
std::vector <Edge> E;

int n, m, S, D;
long long flux;
struct Edgg{
    int dest;
    int ind, revind;
};
std::vector <Edgg> G[1 + MAXN];
long long C[6 * MAXN];
int father[1 + MAXN];
int indd[1 + MAXN];
int revindd[1 + MAXN];

std::queue <int> q;
inline bool bfs(){
    memset(father, 0, sizeof(father));
    while(!q.empty()) q.pop();
    q.push(S);
    father[S] = -1;
    while(!q.empty()){
        int node = q.front();
        q.pop();
        if(node != D)
            for(auto y:G[node])
                if(!father[y.dest] && C[y.ind]) father[y.dest] = node, indd[y.dest] = y.ind, revindd[y.dest] = y.revind, q.push(y.dest);
    }
    return father[D];
}

inline void maximum_flow(int start, int finish){
    S = start, D = finish;
    while(bfs())
        for(auto y:G[D])
            if(father[y.dest] && C[y.revind]){
                father[D] = y.dest;
                indd[D] = y.revind;
                revindd[D] = y.ind;
                long long flow = 100000000000000001;
                for(int i = D; i != S && flow; i = father[i]) flow = std::min(flow, C[indd[i]]);
                if(flow) for(int i = D; i != S; i = father[i]) C[indd[i]] -= flow, C[revindd[i]] += flow;
                flux += flow;
            }
}

int main(){
    FILE*fi,*fo;
    fi = fopen("maxflow.in","r");
    fo = fopen("maxflow.out","w");
    //fi = stdin;
    //fo = stdout;

    fscanf(fi,"%d", &n);
    /*int minx = 2000000001, maxx = -2000000001;
    for(int i = 1; i <= n; i++){
        int x, y;
        fscanf(fi,"%d%d", &x, &y);
        if(x < minx) minx = x, S = i;
        if(x > maxx) maxx = x, D = i;
    }*/
    S = 1, D = n;
    fscanf(fi,"%d", &m);
    for(int i = 1; i <= m; i++){
        int x, y, c;
        fscanf(fi,"%d%d%d", &x, &y, &c);
        E.push_back({x, y, c});
        G[x].push_back({y, 2 * i - 1, 2 * i});
        G[y].push_back({x, 2 * i, 2 * i - 1});
        C[2 * i - 1] = c;
        C[2 * i] = 0;
    }
    maximum_flow(S, D);
    fprintf(fo,"%lld\n", flux);
    /*int ind = 1;
    for(auto e: E){
        if(e.c - C[2 * ind - 1] >= 0) fprintf(fo,"%d %d %lld\n", e.x, e.y, 1LL * e.c - C[2 * ind - 1]);
        else fprintf(fo,"%d %d %lld\n", e.y, e.x, C[2 * ind - 1] - 1LL * e.c);
        ind++;
    }*/

    return 0;
}