Cod sursa(job #2373570)

Utilizator Tataru_AdelinTataru Adelin Tataru_Adelin Data 7 martie 2019 14:17:01
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.32 kb
#include <bits/stdc++.h>

using namespace std;

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

void reset(vector <int> &v)
{
    for(unsigned i = 0; i < v.size(); i++)
        v[i] = 0;
}

void reset(vector <bool> &v)
{
    for(unsigned i = 0; i < v.size(); i++)
        v[i] = false;
}

bool BFS(int start, int dest, vector <vector <int>> &path, vector <vector <int>> &flux, vector <int> &parent, vector <bool> &vis)
{
    reset(vis);
    reset(parent);

    queue <int> q;

    q.push(start);
    vis[start] = true;

    int now, vec;

    while(!q.empty())
    {
        now = q.front();
        q.pop();

        for(unsigned i = 0; i < path[now].size(); i++)
        {
            vec = path[now][i];
            if(!vis[vec] && flux[now][vec])
            {
                parent[vec] = now;
                q.push(vec);
                vis[vec] = true;

                if(vec == dest)
                {
                    return true;
                }
            }
        }
    }

    return false;
}

void update(int start, int dest, int &ans, vector <vector <int>> &path, vector <vector <int>> &flux, vector <int> &parent, vector <bool> &vis)
{
    int now, vec, max_flux;
    for(unsigned k = 0; k < path[dest].size(); k++)
    {
        vec = path[dest][k];

        if(vis[vec] && flux[vec][dest])
        {
            parent[dest] = vec;

            max_flux = flux[vec][dest];

            for(now = parent[dest], vec = dest; vec != start; vec = now, now = parent[now])
            {
                max_flux = min(max_flux, flux[now][vec]);
            }

            for(now = parent[dest], vec = dest; vec != start; vec = now, now = parent[now])
            {
                flux[now][vec] -= max_flux;
                flux[vec][now] += max_flux;
            }

            ans += max_flux;

        }
    }
}

int main()
{
    int n, m;
    fin>>n>>m;

    vector <vector <int>> path(n + 1);
    vector <vector <int>> flux(n + 1, vector <int> (n + 1));


    for(int x, y, f; m; m--)
    {
        fin>>x>>y>>f;
        path[x].push_back(y);
        path[y].push_back(x);

        flux[x][y] = f;
    }

    int ans = 0;
    vector <int> parent(n + 1);
    vector <bool> vis(n + 1);

    while(BFS(1, n, path, flux, parent, vis))
    {
        update(1, n, ans, path, flux, parent, vis);
    }

    fout<<ans<<'\n';

    return 0;
}