Cod sursa(job #2697704)

Utilizator Iulia25Hosu Iulia Iulia25 Data 19 ianuarie 2021 13:17:49
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

ifstream cin ("maxflow.in");
ofstream cout ("maxflow.out");

queue <int> q;
vector <int> v[1005], aux;

int c[1005][1005];

int anterior[1005], cost[1005];
int ans, n, m;
bool ok = true;

void reinit()  {
  memset(anterior, 0, sizeof(anterior));
  memset(cost, 0, sizeof(cost));
  cost[1] = 2e9;
  while (!q.empty())
    q.pop();
  ok = false;
  aux.clear();
}

void bfs();

void reconstituire(int x)  {
  int nod = x;
  cost[n] = min(cost[x], c[x][n]);
  if (cost[n] == 0)
    return;
  while (nod != 1)  {
    if (c[anterior[nod]][nod] < cost[n])
      cost[n] = c[anterior[nod]][nod];
    nod = anterior[nod];
  }
  if(cost[n] == 0)
    return;
  c[x][n] -= cost[n];
  c[n][x] += cost[n];
  nod = x;
  while (nod != 1)  {
    c[anterior[nod]][nod] -= cost[n];
    c[nod][anterior[nod]] += cost[n];
    nod = anterior[nod];
  }
  ok = true;
  ans += cost[n];
}

void bfs()  {
  reinit();
  q.push(1);
  while (!q.empty())  {
    int nod = q.front();
    q.pop();
    if (c[nod][n] > 0)  {
      aux.push_back(nod);
    }
    for (auto it : v[nod])  {
      if (c[nod][it] == 0 || cost[it] || it == n)
        continue;
      cost[it] = min(cost[nod], c[nod][it]);
      anterior[it] = nod;
      q.push(it);
    }
  }
}

int main()  {
  cin >> n >> m;
  int x, y, z;
  for (int i = 1; i <= m; ++i)  {
    cin >> x >> y >> z;
    c[x][y] = z;
    v[x].push_back(y);
    v[y].push_back(x);
  }
  while(ok) {
    bfs();
    for (auto it : aux)  {
      reconstituire(it);
    }
  }
  cout << ans;
	return 0;
}