Cod sursa(job #2266680)

Utilizator DavidLDavid Lauran DavidL Data 22 octombrie 2018 20:31:10
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
ifstream fi("maxflow.in");
ofstream fo("maxflow.out");

const int NMAX = 1005;
const int MMAX = 5005;
const int INF = (1e9);

int n, m;
vector <int> G[NMAX];
int C[NMAX][NMAX], F[NMAX][NMAX];
int p[NMAX];
bool viz[NMAX];
queue <int> Q;

int bfs()
{
   memset(viz, 0, sizeof(viz));
   memset(p, 0, sizeof(p));

   Q.push(1);
   viz[1] = 1;

   while (!Q.empty())
   {
      int nod = Q.front();
      Q.pop();

      for (auto v: G[nod])
      {
         if (C[nod][v] == F[nod][v] || viz[v])
            continue;

         viz[v] = 1;
         Q.push(v);
         p[v] = nod;
         cout << v << " ";

         if (v == n)
            return 1;
      }
   }
}

int main()
{
   fi >> n >> m;
   for (int i = 1; i <= m; i++)
   {
      int u, v, c;
      fi >> u >> v >> c;
      G[u].pb(v);
      G[v].pb(u);
      C[u][v] = c;
   }

   int flux = 0;

   while (bfs())
   {
      int minim = INF;
      for (int nod = n; nod != 1; nod = p[nod])
      {
         minim = min(minim, C[p[nod]][nod] - F[p[nod]][nod]);
      }

      for (int nod = n; nod != 1; nod = p[nod])
      {
         F[p[nod]][nod] += minim;
         F[nod][p[nod]] -= minim;
      }

      flux += minim;
   }
   fo << flux;
   return 0;
}