Cod sursa(job #889848)

Utilizator desoComan Andrei deso Data 24 februarie 2013 18:40:56
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <vector>
#include <fstream>
#include <cstring>
using namespace std;

#define INFILE "maxflow.in" 
#define OUTFILE "maxflow.out"
#define NMAX 1001
#define INF 0x3f3f3f3f

ifstream fin(INFILE);
ofstream fout(OUTFILE);

vector<int>::iterator it;
int n, maxflow;
vector<int> e[NMAX];
int cap[NMAX][NMAX], f[NMAX][NMAX], pre[NMAX], coada[NMAX];
int vis[NMAX];

int bfs() {
   // bfs from start to destination
   for(int i=2; i<=n; i++)
      vis[i] = 0;
   coada[0] = 1;
   vis[1] = 1;
   pre[1] = -1;
   for(int cd = 0, u = 0;  cd<=u; cd++ ) {
      int nod = coada[cd];
      if( nod==n ) continue;

      // pass all neighbours, add them to queue if not destination
      for(it=e[nod].begin(); it!=e[nod].end(); it++) 
         // neighbour not visited and there is still capacity on edge
         if( !vis[*it] && cap[nod][*it]>f[nod][*it] ) {
            vis[*it] = 1;
            pre[*it] = nod;
            coada[++u] = *it;
         }
   }
   // return if it is still possible to reach the destination
   return vis[n];
}

int main() {
   int m, a, b, c;
   fin >> n >> m;
   while(m--) {
      fin >> a >> b >> c;
      e[a].push_back(b);
      e[b].push_back(a);
      cap[a][b] = c;
   }

   for(maxflow = 0; bfs(); ) {
      // traverse all nodes that can lead to destination
      for(it=e[n].begin(); it!=e[n].end(); it++)
         if( vis[*it] && cap[*it][n]>f[*it][n] ) {
            int flow = INF;
            for(int nod = n; nod!=1; nod = pre[nod])
               flow = min(flow, cap[pre[nod]][nod] - f[pre[nod]][nod]);

            if(!flow) continue;
            maxflow += flow;
            for(int nod = n; nod!=1; nod = pre[nod]) {
               f[pre[nod]][nod] += flow;
               f[nod][pre[nod]] -= flow;
            }
         }
   }
   fout << maxflow;
   fin.close();
   fout.close();
   return 0;
}