Cod sursa(job #1982726)

Utilizator M.AndreiMuntea Andrei Marius M.Andrei Data 20 mai 2017 02:19:50
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.68 kb
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <set>
#include <vector>
#include <cstdio>
#include <string.h>
#include <string>
#include <queue>
using namespace std;

#define ll long long
#define ull unsigned long long

/*------------------------------------------------------------------*/


ifstream f{"maxflow.in"};
ofstream q{"maxflow.out"};

int capacity[1005][1005];
int flow[1005][1005];

int n, m;
bool vis[1005];
vector<int> prec(1005, 0);
vector<int> coada(1005, 0);
vector<int> graph[1005];

bool bfs(int source, int destination)
{
   int top;
   int leftQ, rightQ;

   memset(vis, false, sizeof(vis));

   vis[source] = true;
   prec[source] = source;
   coada[1] = source;

   leftQ = 1;
   rightQ = 1;

   while (leftQ <= rightQ)
   {
      top = coada[leftQ];
      if (top == n) goto Continue; //it's target. we can't go further
      for (auto& vecin : graph[top])
      {
         if (!vis[vecin] && capacity[top][vecin] != flow[top][vecin])
         {
            vis[vecin] = true;
            rightQ++;
            coada[rightQ] = vecin;
            prec[vecin] = top;
         }
      }
   Continue:
      leftQ++;
   }

   return vis[destination];
}

int FordFulkerson(int source, int destination)
{
   int maxFlow = 0;
   int localFlow;
   int node;

   while (bfs(source, destination))
   {
      // check all possible roads
      for (size_t i = 0; i < graph[destination].size(); ++i)
      {
         node = graph[destination][i];
         // dead-end
         if (!vis[node] || capacity[node][destination] == flow[node][destination]) continue;

         localFlow = numeric_limits<int>::max();
         prec[destination] = node;
         node = destination;


         while (node != source)
         {
            localFlow = min(localFlow, capacity[prec[node]][node] - flow[prec[node]][node]);
            node = prec[node];
         }

         node = destination;
         while (node != source)
         {
            flow[prec[node]][node] += localFlow;
            flow[node][prec[node]] -= localFlow;
            node = prec[node];
         }

         maxFlow += localFlow;
      }
   }

   return maxFlow;
}

int main()
{
   ios_base::sync_with_stdio(false) , cin.tie(nullptr) , cout.tie(nullptr);

   f >> n >> m;
   int x, y, cap;

   for (int i = 1; i <= m; ++i)
   {
      f >> x >> y >> cap;
      graph[x].push_back(y);
      graph[y].push_back(x);

      capacity[x][y] = cap;
   }
   
   q << FordFulkerson(1, n);

   f.close();
   q.close();
   return 0;
}