dists_t dijkstra_shortest_path(graph_t g, vert_t s) { set<pair<dist_t, vert_t> > q; // implicit ordering by distance // ps_t ps(g.size(), -1); dists_t dists(g.size(), dist_infty); dists[s] = 0; q.insert(make_pair(dists[s], s)); while( !q.empty() ) { dist_t dist = q.begin()->first; vert_t v = q.begin()->second; q.erase( q.begin() ); // pop first for(int i=0; i<g[v].size(); i++) { vert_t t = g[v][i].to; dist_t d_with = dist + g[v][i].len; if( d_with < dists[t] ) { // relax q.erase( make_pair(dists[t], t) ); q.insert( make_pair(d_with, t) ); dists[t] = d_with; // ps[t] = v; } } } return dists; }
path_ps_t bfs( graph_t g, capmat_t caps, vert_t s, vert_t t ) { path_ps_t ps( g.size(), -1 ); // parents ps[s] = s; queue<vert_t> q; q.push(s); while( !q.empty() ) { vert_t u = q.front(); q.pop(); if( u == t ) return ps; for( int i=0; i<g[u].size(); i++ ) { vert_t v = g[u][i]; if( ps[v] < 0 && caps[u][v] > 0 ) { ps[v] = u; q.push(v); } } } }
// solve minimun cost flow problem from s to t to flow f double min_cost_flow(graph_t &graph, int s, int t, int f, bool display_progress) { int V = graph.size(); // number of vertices vector<double> h(V, 0); // potential vector<double> dist(V, INF); // minimum distance from s vector<int> prevv(V, 0); // previous vertex vector<int> preve(V, 0); // previous edge double ret = 0; Progress progress(f, display_progress); while (f > 0) { if (Progress::check_abort()) return RET_ABORTED; // Dijkstra algorithm priority_queue<Pair, vector<Pair>, greater<Pair> > que; fill(dist.begin(), dist.end(), INF); dist[s] = 0; que.push(Pair(0, s)); while (!que.empty()) { Pair p = que.top(); int v = p.second; double d = p.first; que.pop(); if (dist[v] < d) continue; for (int i = 0; i < (int)graph[v].size(); i++) { edge_t &e = graph[v][i]; d = dist[v] + e.cost + h[v] - h[e.to]; if (dist[v] > d) d = dist[v]; // for rounding error if (e.capacity > 0 && dist[e.to] > d) { dist[e.to] = d; prevv[e.to] = v; preve[e.to] = i; que.push(Pair(dist[e.to], e.to)); } } } // no solution if (dist[t] == INF) return RET_NO_SOLUTION; // update potential for (int v = 0; v < V; v++) h[v] += dist[v]; int d = f; for (int v = t; v != s; v = prevv[v]) d = min(d, graph[prevv[v]][preve[v]].capacity); f -= d; progress.increment(d); ret += d * h[t]; for (int v = t; v != s; v = prevv[v]) { edge_t &e = graph[prevv[v]][preve[v]]; e.capacity -= d; graph[v][e.rev].capacity += d; } } return ret; }
int DFA::allocPoint() { int newNode = m_graph.size(); m_graph.emplace_back(); return newNode; }