Cod sursa(job #3234823)

Utilizator handicapatucavasi eduard handicapatu Data 11 iunie 2024 22:09:57
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

int n, m, x, y, z, source, tank, flow;
int graph[1001][1001];
int visited[1001], parent[1001];
int residual_graph[1001][1001];
vector < int > ADJ[1001];

bool bfs(){
    for(int i = 1; i <= n; ++i)
        visited[i] = 0;
    queue < int > Q;
    Q.push(source);
    visited[source] = 1;
    parent[source] = -1;
    while(!Q.empty()){
        int now = Q.front();
        Q.pop();
        for(auto it: ADJ[now]){
            if(residual_graph[now][it] > 0 && visited[it] == 0){
                if(it == tank){
                    parent[it] = now;
                    return true;
                }
                visited[it] = 1;
                parent[it] = now;
                Q.push(it);
            }
        }
    }
    return false;
}

void maxflow(){
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            residual_graph[i][j] = graph[i][j];
    while(bfs()){
        int minim = 2000000000;
        int temp = tank;
        while(temp != source){
            if(residual_graph[parent[temp]][temp] < minim)
                minim = residual_graph[parent[temp]][temp];
            temp = parent[temp];
        }
        flow += minim;
        temp = tank;
        while(temp != source){
            int u = parent[temp];
            int v = temp;
            temp = parent[temp];
            residual_graph[u][v] -= minim;
            residual_graph[v][u] += minim;
        }
    }
}

int main()
{
    f >> n >> m;
    source = 1, tank = n;
    for(int i = 1; i <= m; ++i){
        f >> x >> y >> z;
        graph[x][y] = z;
        ADJ[x].push_back(y);
        ADJ[y].push_back(x);
    }
    maxflow();
    g << flow;
    return 0;
}