Cod sursa(job #3150896)

Utilizator victorzarzuZarzu Victor victorzarzu Data 18 septembrie 2023 22:55:17
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>

using namespace std;
#define oo 0x3f3f3f3f;

ifstream f("maxflow.in");
ofstream g("maxflow.out");
int n, m;
vector<int> graph[1001];
int t[1001], C[1001][1001], F[1001][1001];
bool viz[1001];

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

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

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

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

    if(node == n) {
      continue;
    }

    for(const auto& ngh : graph[node]) {
      if(viz[ngh] || F[node][ngh] == C[node][ngh]) {
        continue;
      } 

      viz[ngh] = true;
      t[ngh] = node;
      q.push(ngh);
    }
  }

  return viz[n];
}

void solve() {
  int result = 0;

  for(;bfs();) {
    for(const auto& ngh : graph[n]) {
      if(!viz[ngh] || F[ngh][n] == C[ngh][n]) {
        continue;
      }

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

      for(int node = n;node != 1;node = t[node]) {
        F[t[node]][node] += flow;
        F[node][t[node]] -= flow;
      }
      result += flow;
    }
  }
  g<<result;
}

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