Cod sursa(job #889709)

Utilizator desoComan Andrei deso Data 24 februarie 2013 17:47:04
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
#include <vector>
#include <iostream>
#include <fstream>
#include <cstring>
#include <queue>
#include <string>
using namespace std;

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

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

vector<int>::iterator it;
int n, s, d;
vector<int> e[NMAX];
int cost[NMAX][NMAX], pre[NMAX];
bool vis[NMAX];

int bfs() {
   // bfs from start to destination
   memset(vis, 0, sizeof(vis));
   queue<int> q;
   q.push(s);
   vis[s] = 1;
   pre[s] = -1;
   while( !q.empty() ) {
      int nod = q.front();
      q.pop();
      if( nod==d ) 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] && cost[nod][*it] ) {
            vis[*it] = 1;
            pre[*it] = nod;
            q.push(*it);
         }
   }
   // return if it is still possible to reach the destination
   return vis[d];
}

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);
      cost[a][b] = c;
   }

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

            if(!flow) continue;
            maxflow += flow;
            nod = d;
            while( pre[nod]!=-1 ) {
               cost[pre[nod]][nod] -= flow;
               cost[nod][pre[nod]] += flow;
               nod = pre[nod];
            }
         }
   }
   fout << maxflow;

   return 0;
}