boolbfs(int i, int t) { c.clear(); c.resize(110, MAX);//存放最大流量 path.clear(); path.resize(110, -1); path[i] = -1;//路径,前缀节点 queue<int> q; q.push(i); visited.clear(); visited.resize(110, false); visited[i] = true; while (!q.empty()) { int x = q.front(); q.pop(); map<int, longlong>::iterator iter; for (iter = last[x].begin(); iter != last[x].end(); iter++) { if ((!visited[iter->first]) && (iter->second > 0)) { q.push(iter->first); path[iter->first] = x; visited[iter->first] = true; c[iter->first] = min(iter->second, c[x]);//更新最小流量 if (iter->first == t) { returntrue; } } } } returnfalse; }
核心代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
voidFordFulker(int n, int s, int t) { longlong ans = 0; while (bfs(s, t)) { for (int i = t; i != s; i = path[i]) { int pre = path[i]; last[pre][i] -= c[t]; last[i][pre] += c[t]; } ans += c[t]; } cout << ans << endl; }
longlongdfs(int u, int t, longlong limit, int s, int n) { if (u == t) { return limit; } longlong mid = limit; map<int, longlong>::iterator iter; for (iter = next(last[u].begin(), cur[u]); iter != last[u].end(); iter++) { if (iter->second > 0 && depth[iter->first] + 1 == depth[u]) { longlong tmp = dfs(iter->first, t, min(mid, iter->second), s, n); if (tmp) { mid -= tmp; iter->second -= tmp; // 可流出量减少 last[iter->first][u] += tmp; // 反向边增加 if (mid <= 0) { return limit; } } } cur[u]++; // 当前弧优化,表示对于节点u我们已经遍历到了第cur[u]条边 } gap[depth[u]]--; if (gap[depth[u]] == 0) // 出现断层 depth[s] = n + 1; depth[u]++;//当前节点深度增加 gap[depth[u]]++;
return limit - mid; }
ISAP
1 2 3 4 5 6 7 8 9 10 11 12 13 14
voidISAP(int n, int s, int t) { longlong ans = 0; bfs(t, s); while (depth[s] <= n) { for (int i = 1; i <= n; i++) { cur[i] = 0; } ans += dfs(s, t, MAX, s, n); } cout << ans << endl; }