Cod sursa(job #584903)

Utilizator Smaug-Andrei C. Smaug- Data 26 aprilie 2011 22:55:21
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <cstdio>
#include <cstdlib>
#include <string>
#define MAXN 1000
#define MAXM 5000
#define INF 2000000000

typedef struct Node {
  int dest;
  Node *next;
} Node;

int F[MAXN+10][MAXN+10], C[MAXN+10][MAXN+10];
int AP[MAXN+10], N, M, viz[MAXN+10], Q[MAXN+10], qpos;

Node *G[MAXN+1];

int BFS(){

  memset(viz, 0, sizeof(viz));

  int i, node;
  Node *aux;

  qpos=0;
  Q[0]=1;
  viz[1]=1;
  
  for(i=0; i<=qpos; i++){
    node=Q[i];
    if(node==N)
      continue;

    for(aux=G[node]; aux!=NULL; aux=aux->next){
      if(C[node][aux->dest]==F[node][aux->dest] || viz[aux->dest])
	continue;
      viz[aux->dest]=1;
      Q[++qpos]=aux->dest;
      AP[aux->dest]=node;
    }

  }

  return viz[N];

}

int main(){

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

  scanf("%d%d", &N, &M);

  int i, j, a, b, c, flow, fmin;
  Node *aux;

  memset(G, NULL, sizeof(G));
  for(i=1; i<=N; i++){
    memset(F[i], 0, sizeof(F[i]));
    memset(C[i], 0, sizeof(C[i]));
  }

  for(i=1; i<=M; i++){
    scanf("%d%d%d", &a, &b, &c);
    C[a][b]+=c;

    aux=new Node;
    aux->dest=b;
    aux->next=G[a];
    G[a]=aux;

    aux=new Node;
    aux->dest=a;
    aux->next=G[b];
    G[b]=aux;
  }

  for(flow=0; BFS(); ){
    for(aux=G[N]; aux!=NULL; aux=aux->next){
      
      if(C[aux->dest][N]==F[aux->dest][N] || !viz[aux->dest])
	continue;

      fmin=INF; 
      for(j=N; j!=1; j=AP[j])
	fmin = (fmin<C[AP[j]][j]-F[AP[j]][j])? fmin: C[AP[j]][j]-F[AP[j]][j];
      if(!fmin)
	continue;
      
      for(j=N; j!=1; j=AP[j]){
	F[AP[j]][aux->dest] += fmin;
	F[aux->dest][AP[j]] -= fmin;
      }

      flow += fmin;
    }
  }

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

}