Cod sursa(job #2368391)

Utilizator dacianouaPapadia Mortala dacianoua Data 5 martie 2019 15:52:23
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <vector>
#include <stdio.h>
#include <string.h>
#define inf 0x3f3f3f3f
#define MAXN 1000
int n, m, S, D, flux;
std::vector <int> G[1 + MAXN];
int C[1 + MAXN][1 + MAXN];
int father[1 + MAXN];
int q[1 + MAXN], p, u;
inline bool bfs(){//paurcurge in latime, cand ajunge la nodul destinatie il ignora si continua pana a vizitat toti vecinii nodului destinatie si apoi scade fluxul parcurgand tatii
    memset(father, 0, sizeof(father));
    p = 0, u = 1;
    q[0] = S;
    while(p != u){
        int node = q[p++];
        if(node != D)
            for(auto y:G[node])
                if(!father[y] && C[node][y]) father[y] = node, q[u++] = y;
    }
    return father[D];
}
int main(){
    FILE *fi,*fo;
    fi = fopen("maxflow.in","r");
    fo = fopen("maxflow.out","w");
    fscanf(fi,"%d%d", &n, &m);
    for(int i = 1; i <= m; i++){
        int x, y, z;
        fscanf(fi,"%d%d%d", &x, &y, &z);
        G[x].push_back(y);
        G[y].push_back(x);
        C[x][y] += z;//fluxul maxim pe muchia x->y
    }
    S = 1, D = n;
    while(bfs())//cat timp se gaseste un drum
        for(auto y:G[D])//dupa ce se face parcurgerea in latime se fac parcurgerile tatilor pornind de la nodul destinatie
            if(father[y] && C[y][D]){
                father[D] = y;
                int flow = inf;
                for(int i = D; i != S && flow; i = father[i]) flow = std::min(flow, C[father[i]][i]);//cauta minimum flow posibil
                if(flow) for(int i = D; i != S; i = father[i]) C[father[i]][i] -= flow, C[i][father[i]] += flow;//adauga flow in muchie directa si scade flow pt muchia inversa
                flux += flow;
            }
    fprintf(fo,"%d", flux);
    return 0;
}