Cod sursa(job #2874745)

Utilizator NanuGrancea Alexandru Nanu Data 20 martie 2022 10:25:53
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

#define DIM 1000
#define INF (1LL << 30)

int n, m;
int C[DIM + 1][DIM + 1], F[DIM + 1][DIM + 1], t[DIM + 1];
vector <int> G[DIM + 1];

static inline bool Bfs(int S, int D) {
  for(int i = 1; i <= n; i++)
    t[i] = 0;
  t[S] = -1;      //sursa;

  queue <int> Q;
  Q.push(S);
  bool ok = 0;
  while(!Q.empty()) {
    int nod = Q.front();
    Q.pop();
    for(auto e : G[nod])
      if(!t[e] && C[nod][e] > F[nod][e])
        if(e != D) {    //daca nu e destinatia;
          t[e] = nod;
          Q.push(e);
        }else ok = 1;
  }
  return ok;
}

static inline int Dinic(int S, int D) {
  int flux = 0;
  for(int drum = Bfs(S, D); drum; drum = Bfs(S, D)) {   //iau toate drumurile pana la D;
    for(auto e : G[D]) {              //pe unde pot ajunge la D;
      if(t[e] && C[e][D] > F[e][D]) {
        t[D] = e; //pe unde am ajuns la destinatie;

        int minim = INF;
        int nod = D;
        while(nod != S) {
          minim = min(minim, C[t[nod]][nod] - F[t[nod]][nod]);
          nod = t[nod];
        }
        if(minim <= 0)
          continue; 
        
        flux += minim;
        nod = D;
        while(nod != S) {
          F[t[nod]][nod] += minim;
          F[nod][t[nod]] -= minim;
          nod = t[nod];
        }
      }
    }
  }

  return flux;
}

int main() {
  fin >> n >> m;
  for(int i = 1; i <= m; i++) {
    int x, y;

    fin >> x >> y >> C[x][y];
    G[x].push_back(y);
    G[y].push_back(x);
  }

  fout << Dinic(1, n);

  return 0;
}