Cod sursa(job #2960732)

Utilizator adeladanescuAdela Danescu adeladanescu Data 4 ianuarie 2023 21:33:59
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <iostream>
#include <fstream>
#include <climits>
#include <vector>
#include <queue>

using namespace std;

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

int N, M, maxim=INT_MAX, temp, next, path_flow;
long max_flow;
vector<vector<int>> capacitate;
vector<int> parinte;
vector<vector<int>> la;

void read(){
    for(int i = 1; i <= M; i++)
    {
        int x, y;
        long z;
        fin >> x >> y >> z;
        la[x].push_back(y);
        la[y].push_back(x);
        capacitate[x][y] = z;
    }
}

int bfs()
{
    vector<bool> viz(N+1);
    queue<int> coada;
    coada.push(1);
    viz[1] = true;
    parinte[1] = -1;
    while(!coada.empty())
    {
        int u = coada.front();
        coada.pop();
        for(auto v: la[u])
        {
            if(capacitate[u][v]!=0 && !viz[v])
            {
                parinte[v] = u;
                if(v == N)
                    return 1;
                coada.push(v);
                viz[v] = true;
            }
        }
    }
    return 0;
}

void maxflow()
{
    int new_flow=bfs();
    while(new_flow)
    {
        int next=N, temp, path_flow = maxim;
        while(next != 1)
        {
            temp = parinte[next];
            path_flow=min(capacitate[temp][next],path_flow);
            next = parinte[next];
        }
        next=N;
        while(next != 1)
        {
            temp = parinte[next];
            capacitate[temp][next] -= path_flow;
            capacitate[next][temp] += path_flow;
            next = parinte[next];
        }
        max_flow = max_flow + path_flow;
        new_flow=bfs();
    }
    fout<<max_flow;

}

int main()
{
    fin >> N >> M;
    capacitate.resize(N+1, vector<int>(N+1));
    parinte.resize(N + 1);
    la.resize(N + 1);
    read();
    maxflow();
    return 0;
}