#pragma warning(disable:4996)
#include<iostream>
#include<string.h>
#include<queue>
#include<stack>
#include<math.h>
#include<map>
#include<set>
#include<algorithm>
#include<sstream>
#include<vector>
#include<ctype.h>
#include<list>
//#include <unordered_map>
#include<deque>
#include<functional>
using namespace std;
#define ll long long
const int N = 4e2 + 10;
const int INF = 0x3f3f3f3f;
int n;
int nx, ny;//两边的点数
ll g[N][N];//二分图描述
ll linker[N], lx[N], ly[N];//y 中各点匹配状态,x,y 中的点标号
ll slack[N];
bool visx[N], visy[N];
int pre[N];
void bfs(int k) {
int x, y = 0, yy = 0;
ll delta;
memset(pre, 0, sizeof pre);
for (int i = 1; i <= ny; i++)slack[i] = 1e13;
linker[y] = (ll)k;
while (1) {
x = linker[y]; delta = 1e13; visy[y] = true;
for (int i = 1; i <= ny; i++) {
if (!visy[i]) {
if (slack[i] > lx[x] + ly[i] - g[x][i]) {
slack[i] = lx[x] + ly[i] - g[x][i];
pre[i] = y;
}
if (slack[i] < delta)delta = slack[i], yy = i;
}
}
for (int i = 0; i <= ny; i++) {
if (visy[i]) {
lx[linker[i]] -= delta;
ly[i] += delta;
}
else slack[i] -= delta;
}
y = yy;
if (linker[y] == -1)break;
}
while (y) {
linker[y] = linker[pre[y]];
y = pre[y];
}
}
ll KM() {
memset(linker, -1, sizeof linker);
memset(lx, 0, sizeof lx);
memset(ly, 0, sizeof ly);
for (int i = 1; i <= ny; i++) {
memset(visy, false, sizeof visy);
bfs(i);
}
ll res = 0;
for (int i = 1; i <= ny; i++)
if (linker[i] != -1)
res += g[linker[i]][i];
return res;
}
int main(void)
{
long long ans = 0;
scanf("%d", &n);
ny = nx = n;
/*得到g[N][N]*/
/*要求最小权值,把g[N][N]变成负的.*/
printf("%lld\n", KM()); //最小权值:-KM().
return 0;
}
MK算法bfs优化模板O(n3)
最新推荐文章于 2024-07-02 10:33:55 发布
这篇博客探讨了如何运用KM算法(Kuhn-Munkres算法,又称匈牙利算法)来解决二分图的最大匹配问题,进而找到图中的最小权值。作者首先展示了KM算法的实现细节,包括松弛操作和增广路径搜索。接着,通过一个实例解释了算法的运行过程,最终求得图的最小权值。这个算法在图论和优化问题中有广泛应用。
摘要由CSDN通过智能技术生成