Cod sursa(job #2808510)

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

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

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

bool bfs()
{
  queue<int> q;
  q.push(1);
  memset(visited, false, sizeof(visited));

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

    if(node == n) continue;
    
    for(auto it : graph[node])
      {
        if(capacity[node][it] == flow[node][it] || visited[it]) continue;
        visited[it] = true;
        q.push(it);
        parent[it] = node;
      }
  }
  return visited[n];
}

void solve()
{
  while(bfs())
  {
    for(auto it : graph[n])
    {
      int node = it;
      if(capacity[node][n] == flow[node][n] || !visited[node]) continue;

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

      for(int nod = n;nod != 1;nod = parent[nod])
        flow_max = min(flow_max, capacity[parent[nod]][nod] - flow[parent[nod]][nod]);
      
      if(!flow_max) continue;

      for(int nod = n;nod != 1;nod = parent[nod])
        flow[parent[nod]][nod] += flow_max, flow[nod][parent[nod]] -= flow_max;
      
      result += flow_max; 
    }
  }
  g<<result;
}

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