二分图匹配
判断无解的情况,当且仅当有 \(a_{i,j}\) 为负数或每一行和每一列的和不相同时无解。
因为 \(m\le N^2\),所以我们只需要每一次至少完成一个 \(a_{i,j}\) 即可。观察 \(B\) 矩阵的形成,实际上就是一个 \(i\) 行只能和一个 \(j\) 列匹配,跑二分图匹配即可。每一次求出 \(B\) 矩阵让其系数为其中所有 \(1\) 位置对应的 \(a_{i,j}\) 的最小值,那么对应的 \(a_{i,j}\) 减去系数后会若干位置会变成 \(0\),此时边 \((i,j)\) 无法选择,退掉。重复上面的操作知道二分图最大匹配 \(\ne n\),结束。
#include <bits/stdc++.h>
#define pii std::pair<int, int>
#define fi first
#define se second
#define pb push_back
using i64 = long long;
using ull = unsigned long long;
const i64 iinf = 0x3f3f3f3f, linf = 0x3f3f3f3f3f3f3f3f;
const int N = 60;
int n;
int a[N][N], vis[N], mat[N], sm1[N], sm2[N], p[N];
bool dfs(int u) {
for (int i = 1; i <= n; i++) {
if(a[u][i] && !vis[i]) {
vis[i] = 1;
if(!mat[i] || dfs(mat[i])) {
mat[i] = u, p[u] = i;
return 1;
}
}
}
return 0;
}
std::vector<std::vector<int> > ans;
void solve() {
memset(sm1, 0, sizeof(sm1));
memset(sm2, 0, sizeof(sm2));
std::cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
std::cin >> a[i][j];
sm1[i] += a[i][j];
sm2[j] += a[i][j];
}
}
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (a[i][j] < 0) {
std::cout << "-1\n";
return;
}
for (int i = 1; i <= n; i++) {
if(sm1[i] != sm1[1] || sm2[i] != sm2[1]) {
std::cout << "-1\n";
return;
}
}
for (int i = 1; i <= n; i++) {
memset(vis, 0, sizeof(vis));
dfs(i);
}
bool ok = 1;
while(ok) {
int mn = iinf;
for (int i = 1; i <= n; i++) {
mn = std::min(mn, a[i][p[i]]);
}
std::vector<int> v;
v.pb(mn);
for (int i = 1; i <= n; i++) {
a[i][p[i]] -= mn;
v.pb(p[i]);
}
ans.pb(v);
for (int i = 1; i <= n; i++) {
if(!a[i][p[i]]) {
mat[p[i]] = 0, p[i] = 0;
memset(vis, 0, sizeof(vis));
if(!dfs(i)) ok = 0; //判断是否仍有增广路
}
}
}
std::cout << ans.size() << "\n";
for (int i = 0; i < ans.size(); i++) {
for (auto x : ans[i]) {
std::cout << x << " ";
}
std::cout << "\n";
}
ans.clear();
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int t;
std::cin >> t;
while (t--) solve();
return 0;
}
标签:二分,Matrix,int,sm2,sm1,qoj5371,long,define
From: https://www.cnblogs.com/FireRaku/p/18278780