Cod sursa(job #2806734)

Utilizator victorzarzuZarzu Victor victorzarzu Data 22 noiembrie 2021 22:30:34
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>
#define oo 0x3f3f3f3f 

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

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

bool bfs()
{
  queue<int> q;
  q.push(1);
  memset(viz, false, sizeof(viz));
  viz[1] = true;

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

    for(auto it : graph[node])
      {
        if(C[node][it] == F[node][it] || viz[it]) continue;

        viz[it] = true;
        q.push(it);
        parent[it] = node;
      }
  }
  return viz[n];
}

void solve()
{
  int flow_max = 0;
  while(bfs())
  {
    for(auto it : graph[n])
    {
      int node = it;

      if(C[node][n] == F[node][n] || !viz[node]) continue;

      int flow_min = oo;
      parent[n] = node;

      for(int nod = n;nod != 1;nod = parent[nod])
        flow_min = min(flow_min, C[parent[nod]][nod] - F[parent[nod]][nod]);
      
      if(!flow_min) continue;
      
      for(int nod = n;nod != 1;nod = parent[nod])
        F[parent[nod]][nod] += flow_min, F[nod][parent[nod]] -= flow_min;

      flow_max += flow_min;
    }
  }
  g<<flow_max;
}

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