Cod sursa(job #2006137)

Utilizator mihai.alphamihai craciun mihai.alpha Data 28 iulie 2017 19:51:06
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <bits/stdc++.h>

using namespace std;

FILE *fin = fopen("maxflow.in", "r");
FILE *fout = fopen("maxflow.out", "w");

int n, m;
int boosted = 1;

vector <int> v[1001];
int cap[1001][1001], flx[1001][1001];
bool viz[1001];
int pre[1001];

inline bool BFS()  {
    queue <int> q;
    memset(viz, 0, sizeof(viz));
    viz[1] = 1;
    q.push(1);
    while(!q.empty())  {
        int nod = q.front();
        q.pop();
        if(nod != n)  {
            for(auto &x : v[nod])
                if(viz[x] == 0 && flx[nod][x] != cap[nod][x])  {
                    viz[x] = 1;
                    pre[x] = nod;
                    q.push(x);
                }
        }
    }
    return viz[n];
}

int main()  {
    fscanf(fin, "%d%d", &n, &m);
    for(int i = 1;i <= m;i++)  {
        int x, y, z;
        fscanf(fin, "%d%d%d", &x, &y, &z);
        v[x].push_back(y);
        v[y].push_back(x);
        cap[x][y] += z;
    }
    int ans = 0, st = 1;
    while(BFS() && st)  {
        int flux;
        for(auto &x : v[n])  {
            if(viz[x] == 1 && flx[x][n] != cap[x][n])  {
                pre[n] = x;
                int sursa = n;
                flux = INT_MAX;
                while(sursa != 1)  {
                    flux = min(flux, cap[pre[sursa]][sursa] - flx[pre[sursa]][sursa]);
                    sursa = pre[sursa];
                }
                if(flux != 0)  {
                    sursa = n;
                    while(sursa != 1)  {
                        flx[pre[sursa]][sursa] += flux;
                        flx[sursa][pre[sursa]] -= flux;
                        sursa = pre[sursa];
                    }
                    ans += flux;
                    boosted++;
                }
            }
        }
    }
    fprintf(fout, "%d", ans);
    fclose(fin);
    fclose(fout);
    return 0;
}