Cod sursa(job #241643)

Utilizator Pepelea_FlaviuFlaviu Pepelea Pepelea_Flaviu Data 10 ianuarie 2009 16:29:51
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
# include <cstdio>
# include <vector>

using namespace std;

# define FIN "maxflow.in"
# define FOUT "maxflow.out"
# define min(A, B) (A < B ? A : B)
# define MFLOW 110000
# define MAXN 1005

int N, M, S, D, n1, n2, c, ct;
int T[MAXN];
int Q[MAXN];
int C[MAXN][MAXN];
vector <int> G[MAXN];
vector <int> :: iterator it;

     int BFS()
     {
         int i;
         
         memset(T, 0, sizeof(T));

         ct = 1;
         Q[1] = S;
         T[S] = -1;

         for (i = 1; i <= ct; ++i)
            for (it = G[Q[i]].begin(); it < G[Q[i]].end(); ++it)
               if (!T[*it] && C[Q[i]][*it])
               {
                   T[*it] = Q[i];
                   if (*it == D) continue;
                   Q[++ct] = *it;
               }

         return T[D];
     }

     int flow()
     {
         int flux, rez = 0, i;

         while (BFS())
            for (it = G[D].begin(); it < G[D].end(); ++it)
               if (C[*it][D] && T[*it])
                  {
                      flux = MFLOW;
                      T[D] = *it;

                      for (i = D; i != S; i = T[i])
                         flux = min(flux, C[T[i]][i]);

                      if (!flux) continue;

                      for (i = D; i != S; i = T[i])
                      {
                          C[T[i]][i] -= flux;
                          C[i][T[i]] += flux;
                      }
                      rez += flux;
                  }
         return rez;
     }

     int main()
     {
         freopen(FIN,"r",stdin);
         freopen(FOUT,"w",stdout);

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

         for (int i = 1; i <= M; ++i)
         {
             scanf("%d%d%d",&n1,&n2,&c);

             G[n1].push_back(n2);
             G[n2].push_back(n1);

             C[n1][n2] = c;
         }

         S = 1; D = N;

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

         return 0;
     }