Cod sursa(job #1692356)

Utilizator PTAdrian64Pop-Tifrea Adrian PTAdrian64 Data 20 aprilie 2016 18:58:46
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <cstdio>
#include <vector>
#define nmax 1001
#include <queue>
#include <cstring>
#define INF 0x3f3f3f3f
#include <algorithm>

using namespace std;

int N,M;
int cap[nmax][nmax],pred[nmax],F[nmax][nmax];
vector <int> G[nmax];
bool viz[nmax];
queue <int> Q;

bool BFS(int s,int d){

  Q.push(s);
  memset(viz,0,sizeof(viz));
  int x;
  viz[s] = 1;
  while(!Q.empty()){
    x = Q.front();
    Q.pop();
    for(vector <int> :: iterator it = G[x].begin();it != G[x].end();++it){
      if(cap[x][*it] == F[x][*it] || viz[*it] == 1)continue;
	pred[*it] = x;
	viz[*it] = 1;
	if(*it == d)return true;
	Q.push(*it);      
    }
  }

  return false;
  
}

int main(){

  freopen("maxflow.in","r",stdin);
  freopen("maxflow.out","w",stdout);

  scanf("%d %d ",&N,&M);
  int x,y,z;
  
  while(M--){
    scanf("%d %d %d ",&x,&y,&z);
    cap[x][y] += z;
    G[x].push_back(y);
    G[y].push_back(x);
  }

  int s = 1,d = N,fmin,flow = 0;
  
  while(BFS(s,d)){

    fmin = INF;
    
    /*y = d;
    while(y != s){

      fmin = min(fmin,cap[pred[y]][y] - F[pred[y]][y]);
      y = pred[y];
      
      }

    y = d;
    while(y != s){

      F[pred[y]][y] += fmin;
      F[y][pred[y]] -= fmin;
      y = pred[y];
      
      }*/

    for(y = d;y != s;y = pred[y])
      fmin = min(fmin,cap[pred[y]][y] - F[pred[y]][y]);
    for(y = d;y != s;y = pred[y]){
      F[pred[y]][y] += fmin;
      F[y][pred[y]] -= fmin;
    }

    flow += fmin;
    
    }

    printf("%d\n",flow);

    //printf("%d\n",BFS(1,N));
  
  return 0;
  
}