题目
解题思路
我们发现只要保证每行每列的最值不变,还有不为0的格子永远不为零即可。
这时候会有某个格子能够同时满足行最大值和列最大值,这种情况是极好的。
因此我们对行列建立二分图,如果
i
i
i行和
j
j
j列最大值相同,且
(
i
,
j
)
(i,j)
(i,j)不为空,即可连边。对此图求带权匹配即可。
我们可以发现,二分图的带权匹配等价于费用流。
代码
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 210;
struct edge {
int to, rev;
ll cap, c;
edge() {}
edge(int to, ll cap, ll c, int rev):to(to), cap(cap), c(c), rev(rev) {}
};
vector<edge> G[N];
ll dis[N], flow[N], fr[N], idx[N];
bool vis[N];
void addedge(int from, int to, ll cap, ll v) {
G[from].push_back(edge(to, cap, v, G[to].size()));
G[to].push_back(edge(from, 0, -v, G[from].size() - 1));
}
ll spfa(int s, int t) {
for (int i = 1; i < N; i++) dis[i] = 1e18, flow[i] = 1e18;
dis[s] = 0;
queue<int> Q;
Q.push(s);
while (!Q.empty()) {
int u = Q.front(); Q.pop();
vis[u] = false;
for (int i = 0; i < G[u].size(); i++) {
edge e = G[u][i];
if (e.cap > 0 && dis[e.to] > dis[u] + e.c) {
dis[e.to] = dis[u] + e.c;
fr[e.to] = u; idx[e.to] = i;
flow[e.to] = min(flow[u], e.cap);
if (!vis[e.to]) {
Q.push(e.to);
vis[e.to] = true;
}
}
}
}
return dis[t] < 1e17;
}
ll MCMF(int s, int t) {
ll ans = 0, f= 0;
while (spfa(s, t)) {
ans += flow[t] * dis[t];
f += flow[t];
ll x = t;
while (x != s) {
edge &e = G[fr[x]][idx[x]];
e.cap -= flow[t];
G[e.to][e.rev].cap += flow[t];
x = fr[x];
}
}
return ans - f;
}
int n, m;
int sa[N][N], col[N], row[N];
int main() {
//freopen("0.txt", "r", stdin);
ll sum = 0, cnt = 0, res = 0;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%d", &sa[i][j]);
col[i] = max(col[i], sa[i][j]);
row[j] = max(row[j], sa[i][j]);
if (sa[i][j]) sum += sa[i][j], cnt++;
}
}
int S = n + m + 1, T = S + 1;
for (int i = 1; i <= n; i++) {
addedge(S, i, 1, 0);
if (col[i]) res += col[i] - 1;
}
for (int i = 1; i <= m; i++) {
addedge(n + i, T, 1, 0);
if (row[i]) res += row[i] - 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (col[i] == row[j] && sa[i][j]) {
addedge(i, n + j, 1, col[i]);
}
}
}
printf("%lld\n", sum - cnt - (res - MCMF(S, T)));
return 0;
}