Cod sursa(job #2695927)

Utilizator YesterdayIlie George Ciprian Yesterday Data 14 ianuarie 2021 21:30:11
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include<bits/stdc++.h>

using namespace std;
ifstream f("maxflow.in");
ofstream o("maxflow.out");
#define INF 110000

int adj[1001][1001];
int n,m;
vector<int> path(1001, 0);
vector<int> v[1001];

void bfs(){
    queue<int> q;
    for(int i = 1;i <= n; i++){
        path[i] = 0;
    }
    q.push(1);
    path[1] = -1;
    while(!q.empty() && !path[n]){
        int curr = q.front();
        q.pop();
        for(auto j: v[curr]){
            if(adj[curr][j]){
                if(!path[j]){
                    path[j] = curr;
                    q.push(j);
                }
            }
        }
    }
}

int dinic(){
    int ans = 0;
    while(true)
        {
        bfs();
        if(path[n] == 0)
            return ans;
        else{
            for(auto pred: v[n])
                {
                int curr = n;
                path[n] = pred;
            if(path[pred] > 0)
                {
                int flow = INF;
                while(path[curr] != -1)
                    {
                    flow = min(flow, adj[path[curr]][curr]);
                    curr = path[curr];
                    }
                curr = n;
                while(path[curr] != -1)
                    {
                    adj[path[curr]][curr] -= flow;
                    adj[curr][path[curr]] += flow;
                    curr = path[curr];
                    }
                        ans += flow;
                    }

                }
        }

    }
}


int main(){
    int x,y,c;
    f>>n>>m;
    for(int i = 0;i<m;i++){
        f>>x>>y>>c;
        adj[x][y] = c;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    o<<dinic();

    return 0;
}