Cod sursa(job #3036560)

Utilizator seburebu111Mustata Dumtru Sebastian seburebu111 Data 24 martie 2023 16:20:46
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int M = 5002;
const int N = 1002;
const int INF = 110002;

int n, m, s, t;
int pred[N];
vector<int> a[N];
int cap[N][N];
int bfs()
{
    for(int i=1; i<=n; i++)
        pred[i]=-1;
    pred[s]=-2;

    queue<pair<int, int>> q;
    q.push({s, INF});

    while(!q.empty()){
        int x=q.front().first;
        int cost = q.front().second;
        q.pop();

        for(auto y: a[x])
        {
            if(pred[y] == -1 && cap[x][y])
            {
                pred[y] = x;
                int newflow = min(cost, cap[x][y]);
                if(y == t)
                    return newflow;
                q.push({y, newflow});
            }
        }
    }
    return 0;
}

int maxflow()
{
    int totalflow = 0;
    int newflow;
    while(newflow = bfs()){
        totalflow +=newflow;
        int y = t;
        while(y!=s){
            int x=pred[y];
            cap[x][y]-=newflow;
            cap[y][x]+=newflow;
            y=x;
        }
    }
    return totalflow;
}

int main()
{
    in>>n>>m;
    s=1; t=n;
    for(int i=1; i<=m; i++)
    {
        int x, y;
        in>>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
        in>>cap[x][y];
    }
    out<<maxflow();
    return 0;
}