Cod sursa(job #2931198)

Utilizator victorzarzuZarzu Victor victorzarzu Data 30 octombrie 2022 17:26:54
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>

#define N 1005
#define oo 0x3f3f3f3f

using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int n, m;
vector<int> graf[N];
int F[N][N], C[N][N];
int t[N];
bool viz[N];

void read() {
  f>>n>>m;
  int x, y;
  for(int i = 1;i <= m;++i) {
    f>>x>>y>>C[x][y];
    graf[x].push_back(y);
    graf[y].push_back(x);
  }
}

bool bfs() {
  memset(viz, false, sizeof(viz));

  viz[1] = true;
  queue<int> q;
  q.push(1);

  while(!q.empty()) {
    int node = q.front();
    q.pop();

    if(node == n) {
      continue;
    }

    for(const auto& vecin : graf[node]) {
      if(viz[vecin] || C[node][vecin] == F[node][vecin]) {
        continue;
      }
      viz[vecin] = true;
      t[vecin] = node;
      q.push(vecin);
    }
  }
  return viz[n];
}


void solve() {
  int result = 0;
  while(bfs()) {
    for(const auto& node : graf[n]) {
      if(!viz[node] || C[node][n] == F[node][n]) {
        continue;
      }
      

      int flow = oo;
      t[n] = node;
      for(int nod = n;nod != 1;nod = t[nod]) {
        flow = min(flow, C[t[nod]][nod] - F[t[nod]][nod]);      
      }
      if(!flow) {
        continue;
      }
      for(int nod = n;nod != 1;nod = t[nod]) {
        F[t[nod]][nod] += flow;
        F[nod][t[nod]] -= flow;
      }
      result += flow;
    }
  }

  g<<result<<'\n';
}

int main() {
  read();
  solve();  
  return 0;
}