1066 ModricWang的水系法术
思路
比较典型的最大流问题,需要注意的是,题目已经暗示(明示)了这里的边是双向的,在建图的时候需要加上反向边的容量值。
解决最大流问题的基本思路就是不断在残量网络上找增广路径,这里可以参考一下我院远古学长Song Renfei对于ISAP算法的讲解:ISAP
时间复杂度(O(V^2 sqrt E))
代码
#include <iostream>
#include <cstring>
using std::ios_base;
using std::cin;
using std::cout;
const int MAXN = 1100;
int maze[MAXN][MAXN];
int gap[MAXN], dis[MAXN], pre[MAXN], cur[MAXN];
int sap(int start, int end, int nodenum) {
memset(cur, 0, sizeof(cur));
memset(dis, 0, sizeof(dis));
memset(gap, 0, sizeof(gap));
int u = pre[start] = start, maxflow = 0, aug = -1;
gap[0] = nodenum;
while (dis[start] < nodenum) {
loop:
for (int v = cur[u]; v < nodenum; v++)
if (maze[u][v] && dis[u]==dis[v] + 1) {
if (aug==-1 || aug > maze[u][v])aug = maze[u][v];
pre[v] = u;
u = cur[u] = v;
if (v==end) {
maxflow += aug;
for (u = pre[u]; v!=start; v = u, u = pre[u]) {
maze[u][v] -= aug;
maze[v][u] += aug;
}
aug = -1;
}
goto loop;
}
int mindis = nodenum - 1;
for (int v = 0; v < nodenum; v++)
if (maze[u][v] && mindis > dis[v]) {
cur[u] = v;
mindis = dis[v];
}
if ((--gap[dis[u]])==0)break;
gap[dis[u] = mindis + 1]++;
u = pre[u];
}
return maxflow;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
memset(maze, 0, sizeof(maze));
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
maze[a][b] = maze[b][a] = c;
}
int ans = sap(1, n, n + 1);
cout << ans << "
";
}