#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 510,INF = 1e18;
ll n,m;
ll a[N][N];
ll ex[N],ey[N],visy[N],now;
ll match[N],pre[N],slack[N];
void bfs(ll u){
ll x,y = 0,yy = 0,d;
memset(pre,0,sizeof pre);
for(int i = 1; i <= n; i++) slack[i] = INF; //需要变小的点
match[y] = u;
while(1){
x = match[y],d = INF,visy[y] = now;
for(int i = 1; i <= n; i++){
if(visy[i] == now) continue;
if(slack[i] > ex[x] + ey[i] - a[x][i]){
slack[i] = ex[x] + ey[i] - a[x][i];
pre[i] = y; //表示 y对应的 点 y 需要减小的权值
}
if(slack[i] < d){
d = slack[i],yy = i; //找出减少最小的那条边
}
}
for(int i = 0; i <= n; i++){
if(visy[i] == now) ex[match[i]] -= d,ey[i] += d;
else slack[i] -= d;
}
y = yy;
if(match[y] == -1) break;
}
while(y){
match[y] = match[pre[y]],y = pre[y]; // 更新每个点对应的点
}
}
int main(){
scanf("%lld%lld",&n,&m);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
a[i][j] = -INF;
}
}
for(int i = 1; i <= m; i++){
ll x,y,w;
scanf("%lld%lld%lld",&x,&y,&w);
a[x][y] = max(a[x][y],w);
}
memset(match,-1,sizeof match);
memset(ex,0,sizeof ex);
memset(ey,0,sizeof ey);
memset(visy,0,sizeof visy);
for(int i = 1; i <= n; i++){
++now;
bfs(i);
}
ll sum = 0;
for(int i = 1; i <= n; i++){
if(match[i] != -1) sum += a[match[i]][i];
}
cout << sum << endl;
for(int i = 1; i <= n; i++){
cout << match[i] << " ";
}
return 0;
}
km算法对最大全职匹配bfs算法的解释理解 n^3
最新推荐文章于 2021-08-02 10:14:16 发布