Cod sursa(job #3261179)

Utilizator TeodorLuchianovTeo Luchianov TeodorLuchianov Data 4 decembrie 2024 17:15:19
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

typedef long long ll;

int const INF = 1e9+7;

struct Edge{
  int from;
  int to;
  int flow; // capacity 
};

int const MMAX = 5000;
Edge e[1 + 2 * MMAX];

int const NMAX = 1000;
vector <int> g[1 + NMAX];
int dist[1 + NMAX];
int parent[1 + NMAX];

bool BFS(int n, int start, int sink) { 
  for(int i = 1;i <= n;i++) {
    dist[i] = INF;
  }
  queue <int> q;
  dist[start] = 0;
  q.push(start);
  while(!q.empty()) {
    int from = q.front();
    q.pop();
    for(int i = 0;i < g[from].size();i++) {
      int to = e[g[from][i]].to, flow = e[g[from][i]].flow;
      //cerr << from << ' ' << to << ' ' << flow << '\n';
      if(flow > 0 && dist[from] + 1 < dist[to]) {
	dist[to] = dist[from] + 1;
	parent[to] = g[from][i];
	q.push(to);
      }
    }
  }
  if(dist[sink] != INF) {
    return true;
  }
  return false;
}

int updatePath(int n, int start, int sink) {
  int minflow = INF;
  for(int node = sink;node != start;node = e[parent[node]].from) {
    minflow = min(minflow, e[parent[node]].flow); 
  }
  for(int node = sink;node != start;node = e[parent[node]].from) {
    e[parent[node]].flow -= minflow;
    e[parent[node]^1].flow += minflow;
  }
  return minflow;
}

ll solve(int n, int start, int sink) {
  ll ans = 0;
  while(BFS(n, start, sink)) {
    //cerr << '\n';
    int add = updatePath(n, start, sink);
    ans += add;
  }
  return ans;
}

int main() {

  int n, m;
  in >> n >> m;
  for(int i = 1;i <= m;i++) {
    int a, b, flow;
    in >> a >> b >> flow;  
    e[2 * i - 2] = {a, b, flow};
    e[2 * i - 1] = {b, a, 0}; 
    g[a].push_back(2 * i - 2);
    g[b].push_back(2 * i - 1);
  }
  out << solve(n, 1, n);
  return 0;
}