网络流EK

时间:2024-09-07 21:35:02
#include <iostream>
#include <queue>
#include <string.h>
#define MAX 302 using namespace std; int c[MAX][MAX];
int pre[MAX];
int visited[MAX];
int n, m; bool Path(int src, int des)
{
queue <int> q; for (int i = ; i <= m; i++)
{
visited[i] = ;
pre[i] = ;
} q.push(src);
visited[src] = ; while (!q.empty())
{
int cur = q.front();
q.pop(); for (int i = ; i <= m; i++)
{
if (!visited[i] && c[cur][i])
{
q.push(i);
pre[i] = cur;
visited[i] = ;
if (i == des)
{
return true;
break;
}
}
}
}
return false;
} int EK(int src, int des)
{
int min, i, total = ; while (true)
{
if (!Path(src, des))
{
break;
} i = des;
min = ( << );
while (i != src)
{
if (min > c[pre[i]][i])
{
min = c[pre[i]][i];
}
i = pre[i];
} i = des;
while (i != src)
{
c[pre[i]][i] -= min;
c[i][pre[i]] += min;
i = pre[i];
} total += min;
} return total;
}
int main()
{
int a, b, f;
while (cin >> n >> m)
{
memset(c, , sizeof(c));
for (int i = ; i < n; i++)
{
cin >> a >> b >> f;
c[a][b] += f;
} cout << EK(, m) << endl;
}
return ;
}

网络流的EK算法,主要就是不断的找增广路,如果找到了增广路,说明流量还可以增加,否则输出最大流即可.

找增广路用到bfs,找到后必须更新残量网络,用增广路的最大流更新残量网络.