Cod sursa(job #2120543)

Utilizator omegasFilip Ion omegas Data 2 februarie 2018 16:28:44
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <fstream>

using namespace std;

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

struct graf{
int nod;
graf* next;
};

int n;

graf* g[1001];
int res[1001][1001];

int flow;
int c[1001];
int q[1001];
int a,b;
int tati[1001];

void add(int a, int b, graf* v[])
{
    graf* q = new graf;
    q->nod  = b;
    q->next = v[a];
    v[a] = q;
}

void BFS(int k){
    graf*  p;
    for(p = g[k]; p!=NULL; p=p->next){
        if(c[p->nod] == 0 && res[k][p->nod] > 0){
            ++b;
            q[b] = p->nod;
            c[p->nod] = 1;
            tati[p->nod] = k;
            if(p->nod == n)
                return;
        }
    }
    ++a;

    if(b >= a)
        BFS(q[a]);
}

void findPath(){

}

void print(){
    int i,j;
for(i=1;i<=n;++i){
    for(j=1;j<=n;++j)
        cout << res[i][j] << " ";
    cout << "\n";
}
cout << flow << "\n";
}


void update(){
    int i;
    c[1] = 1;
    for(i=2;i<=n;++i)
        c[i] = 0;
    a = b = 0;
    q[0] = 1;



    BFS(1);
    if(c[n] == 0)
        return;



    int x = n;
    int minim = 100200;

    while(x != 1){
        if(minim > res[tati[x]][x])
            minim = res[tati[x]][x];
        x = tati[x];
    }
    flow = flow + minim;

    x = n;
    while(x != 1){
        res[tati[x]][x] = res[tati[x]][x] - minim;
        res[x][tati[x]] = res[x][tati[x]] + minim;
        x = tati[x];
    }
    update();
}


int main()
{
    int m,x,y,z,i,j;
    fin >> n >> m;
    for(i=1;i<=m;++i){
        fin >> x >> y >> z;
        add(x,y,g);
        add(y,x,g);
        res[x][y] = z;
    }

    update();

    fout << flow;


    return 0;
}