这段代码,不需要知道题意:
#include <bits/stdc++.h>
#include <bits/extc++.h>
using namespace __gnu_pbds;
using namespace __gnu_cxx;
using namespace std;
int n, m, r, c, mat[13][13], ans = INT_MAX;
vector<array<int, 14>> v1, v2;
array<int, 14> a;
bitset<13> vis;
void Dfs(int x, int n, int r, int s, vector<array<int, 14>> ctn) {
if (x == r + 1) return ctn.push_back(a);
for (int i = s; i <= n; i++) if (!vis[i]) a[x] = i, vis[i] = true, Dfs(x + 1, n, r, i + 1, ctn), vis[i] = false;
}
void get() {
Dfs(1, n, r, 1, v1);
Dfs(1, m, c, 1, v2);
}
void calc() {
int res = 0;
for (auto i : v1) {
for (auto j : v2) {
for (int ii = 1; ii < r; ii++) for (int jj = 1; jj <= c; jj++) res += abs(mat[i[ii]][j[jj]] - mat[i[ii]][j[jj + 1]]) + abs(mat[i[ii]][j[jj]] - mat[i[ii + 1]][j[jj]]);
ans = min(ans, res), res = 0;
}
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
cin >> n >> m >> r >> c;
for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> mat[i][j];
get(), calc();
cout << ans;
return 0;
}
中 ans 不会更新,也就是说 Dfs 失败,原因是什么
给组样例:
7 7 3 3
7 7 7 6 2 10 5
5 8 8 2 1 6 2
2 9 5 5 6 1 7
7 9 3 6 1 7 8
1 9 1 4 7 8 8
10 5 9 1 1 8 10
1 3 1 5 4 8 6
16