Cod sursa(job #2743361)

Utilizator codruta.miron08Miron Ioana Codruta codruta.miron08 Data 22 aprilie 2021 21:01:57
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
// C++ program for implementation of Ford Fulkerson
// algorithm
#include <iostream>
#include <limits.h>
#include <queue>
#include <string.h>
#define MAXN 1001
#include <fstream>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int graph[MAXN][MAXN];
  int graphr[MAXN][MAXN];
  int tata[MAXN];
queue<int> q;
    bool viz[MAXN];
  int n,m;
bool bfs(int st, int dr)
{
    while(!q.empty())
        q.pop();
    memset(viz, 0, sizeof(viz));
    q.push(st);
    viz[st] = true;
    tata[st] = -1;

    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        for (int v = 0; v < n; v++)
        {
            if (viz[v] == false && graphr[nod][v] > 0)
            {
                if (v == dr)
                {
                    tata[v] = nod;
                    return true;
                }
                q.push(v);
                tata[v] = nod;
                viz[v] = true;
            }
        }
    }

    return false;
}

int fordFulkerson(int st, int dr)
{
    int x, y;
   for (x = 0; x < n; x++)
        for (y = 0; y < n; y++)
            graphr[x][y] = graph[x][y];
    int flux_maxim = 0;
    while (bfs(st, dr))
    {
        int minim = 100001;
        for (y = dr; y != st; y = tata[y])
        {
            x = tata[y];
            minim = min(minim, graphr[x][y]);
        }

        for (y = dr; y != st; y = tata[y])
        {
            x = tata[y];
            graphr[x][y] -= minim;
            graphr[y][x] += minim;
        }

        flux_maxim += minim;
    }

    return flux_maxim;
}

int main()
{
    fin >> n >> m;
    while(m--)
    {
        int x,y,c;
        fin >> x >> y >> c;
        graph[x - 1][y - 1] = c;
    }
    fout << fordFulkerson(0,n - 1);
    return 0;
}