Cod sursa(job #3263488)

Utilizator TeodorLuchianovTeo Luchianov TeodorLuchianov Data 14 decembrie 2024 14:38:05
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.22 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

int const NMAX = 500;
int const INF = 1e9+7;

struct Dinic{

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

  vector <Edge> edges;
  int dist[1 + NMAX];
  int edge_ind[1 + NMAX];
  vector <int> g[1 + NMAX];

  void addEdge(int from, int to, int flow) {
    edges.push_back({from, to, flow});
    edges.push_back({to, from, 0});
    g[from].push_back(edges.size()-2);
    g[to].push_back(edges.size()-1);
  }

  void BFS(int source, int n) {
    for(int i = 1;i <= n;i++) {
      dist[i] = INF;
      edge_ind[i] = 0;
    }
    queue <int> q;
    dist[source] = 0;
    q.push(source);
    while(!q.empty()) {
      int from = q.front();
      q.pop();
      for(int i = 0;i < g[from].size();i++) {
	int to = edges[g[from][i]].to, flow = edges[g[from][i]].flow;
	if(flow != 0 && dist[from] + 1 < dist[to]) {
          dist[to] = dist[from] + 1;
	  q.push(to);
	}
      }
    }
  }

  int doPush(int node, int minflow, int sink) {
    if(node == sink) {
      return minflow;
    }else {
      int pushed = 0;
      for(int &i = edge_ind[node];i < g[node].size();i++) {
	int to = edges[g[node][i]].to, flow = edges[g[node][i]].flow;
	if(flow != 0 && dist[node] < dist[to]) {
          int temp = doPush(to, min(minflow - pushed, flow), sink);
	  if(pushed + temp <= minflow) {
	    pushed += temp;
	    edges[g[node][i]].flow -= temp;
	    edges[g[node][i] ^ 1].flow += temp;
	  }
	}
      }
      return pushed;
    }
  }

  int computeMaxflow(int source, int sink, int n) {
    bool finish = false;
    int ans = 0;
    while(!finish) {
      BFS(source, n);
      int pushed = doPush(source, INF, sink);
      ans += pushed;
      if(pushed == 0) {
	finish = true;
      } 
    }
    return ans;
  }
};

Dinic flux;

void buildGraph(int n, int m) {
  for(int i = 1;i <= n;i++) {
    flux.addEdge(i, n + i, 1);
  }
  for(int i = 1;i <= m;i++) {
    int a, b;
    in >> a >> b;
    flux.addEdge(n + a, b, INF);
    flux.addEdge(n + b, a, INF);
  }
}

int main() {

  int n, m, start, stop;
  in >> n >> m >> start >> stop;
  buildGraph(n, m); 
  out << flux.computeMaxflow(n + start, stop, 2 * n);
  return 0;
}