全局最小割
算法:stoer wagner
学习资料:
上交pdf:读懂步骤
stoer wagner详解:读懂正确性证明
然后你就能写出代码了。
上海理工大学第二届“联想杯” Dahno Dahno
无向图最小割模板。
//
// Created by artis on 2021/6/13.
//
#include<bits/stdc++.h>
using namespace std;
const int maxn = 505;
typedef long long ll;
ll a[maxn][maxn]; // 邻接矩阵
const ll inf = 1e18;
int n;
int used[maxn];
ll deg[maxn];
ll stoerWagner(){
ll res = inf;
for(int i=1;i<n;++i){
// repeat n-1 times
for(int j=1;j<=n;++j) deg[j]=0,used[j]=0;
used[1]=1;
for(int j=1;j<=n;++j) deg[j] += a[1][j];
int s=1,t; // s为上一个
for(int j=1;j+i<=n;++j){
// repeat n-i times
s = t;
t = 0;
for(int k=1;k<=n;++k)
// add tightest connected
if(!used[k] && deg[k]>deg[t]) t = k;
used[t]=1;
for(int k=1;k<=n;++k)
deg[k] += a[t][k];
}
// upd
res = min(res,deg[t]);
// 缩点
if(s>t) swap(s,t);
for(int j=1;j<=n;++j){
a[s][j] = a[j][s] += a[t][j];
a[t][j] = a[j][t] = 0;
}
a[s][t] = a[t][s] = 0;
a[s][s] = a[t][t] = 0;
}
return res;
}
int main(){
scanf("%d",&n);
ll sum = 0;
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
scanf("%lld",&a[i][j]);
sum += a[i][j];
}
}
ll cut = stoerWagner();
printf("%lld\n",sum-2*cut);
}