Cod sursa(job #2119368)

Utilizator cameleonGeorgescu Dan cameleon Data 31 ianuarie 2018 23:53:53
Problema Flux maxim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define nmax 10005
#define INF 0x3fffffff
using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
vector <int> g[nmax];
queue <int> q;

int cap[nmax][nmax];
int flow[nmax][nmax];
int t[nmax];
int n,m;
int maxflow;

bool bfs() {
    bool found = false;
    memset(t,0,nmax*4);
    t[0] = t[1] = -1;
    q.push(1);
    while (!q.empty()) {
        int ct = q.front(); q.pop();
        for (vector <int> :: iterator it = g[ct].begin();it != g[ct].end();it++) {
            if (cap[ct][*it] - flow[ct][*it] > 0 && t[*it] == 0) {
                if (*it != n) {
                    q.push(*it);
                    t[*it] = ct;
                } else {
                found= true;
                }
            }
        }
    }
    return found;
}

int getMin(int x) {
    int newMin=INF;
    while (t[x] != -1) {
        newMin= min(newMin,cap[t[x]][x] - flow[t[x]][x]);
        x=t[x];
    }
    return newMin;
}

void update(int x,int value) {
    while (t[x] != -1) {
        flow[t[x]][x] += value;
        flow[x][t[x]] -= value;
        x=t[x];
    }
}

int main() {
    fin>>n>>m;
    for (int i=1;i<=m;i++) {
        int a,b,c;
        fin>>a>>b>>c;
        g[a].push_back(b);
        g[b].push_back(a);
        cap[a][b] = c;
    }
    while (bfs()) {
        for (vector <int> :: iterator it = g[n].begin(); it != g[n].end();it++)
        {
            t[n] = *it;
            if (cap[*it][n] > flow[*it][n] && t[*it] != 0) {
                int min = getMin(n);
                if(min<=0) continue;
                maxflow += min;
                update(n,min);
            }
        }
    }
    fout<<maxflow;
    return 0;
}