Cod sursa(job #2954952)

Utilizator Andra_Gheorghe12Andra Gheorghe Andra_Gheorghe12 Data 15 decembrie 2022 20:43:18
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <limits.h>
#include <queue>
#include <string.h>
#include <fstream>
using namespace std;

int n,m,val,i,graph[1001][5001],x,y;

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

bool bfs(int rGraph[1001][5001],int n, int s, int t, int parent[])
{
    bool visited[n];
    memset(visited, 0, sizeof(visited));
    queue<int> q;
    q.push(s);
    visited[s] = true;
    parent[s] = -1;


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

        for (int v = 1; v <=n; v++) {
            if (visited[v] == false && rGraph[u][v] > 0) {
                if (v == t) {
                    parent[v] = u;
                    return true;
                }
                q.push(v);
                parent[v] = u;
                visited[v] = true;
            }
        }
    }

    return false;
}


int fordFulkerson(int graph[1001][5001],int n, int s, int t)
{
    int u, v;

   // int rGraph[1005][5005];

    //for (u = 1; u <=n; u++)
     //   for (v = 1; v <=n; v++)
           // rGraph[u][v] = graph[u][v];

    int parent[n];
    int max_flow = 0; // There is no flow initially


    while (bfs(graph,n, s, t, parent)) {
        int path_flow = INT_MAX;
        for (v = t; v != s; v = parent[v]) {
            u = parent[v];
            path_flow = min(path_flow, graph[u][v]);
        }


        for (v = t; v != s; v = parent[v]) {
            u = parent[v];
            graph[u][v] -= path_flow;
            graph[v][u] += path_flow;
        }

        max_flow += path_flow;
    }


    return max_flow;
}


int main()
{
    fin>>n>>m;
    for(i=1;i<=m;i++)
    {
        fin>>x>>y>>val;
        graph[x][y]+=val;
    }
    //"The maximum possible flow is "
    fout << fordFulkerson(graph,n, 1, n);

    return 0;
}