深度搜索:
设dfs(x,y,t)表示前x行涂成白色,后y行涂成红色,所花费的代价为t;则递归边界为(x + y >= n),同时进行剪枝,记录已经递归过的x,y,下次遇见直接跳过。
**搜索的思路为:**先固定y,搜索不同x下的最小值,然后固定x,搜索不同y的最小值,得到最小的代价
代码如下
#include <iostream>
#include <cstdio>
#include <numeric>
#include <functional>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
#include <bitset>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int maxn = 1e6 + 3;
const int N = 1e5 + 5;
int n, m;
int a[55][4];
int flag;//是否完成输出
int ans = 0x3ffffff;
int used[55][55];
int dfs(int x ,int y ,int t) {
if (x + y >= n) return 0;
if (used[x][y]) return 0;//剪枝,避免重复
used[x][y] = 1;
if (x > 0 && y > 0 && x + y < n) {
int k = 0;
for (int i = x + 1; i <= n - y; ++i) {
k += a[i][1];
k += a[i][3];
}
ans = min(ans, t + k);
}
dfs(x + 1, y, t + a[x + 1][2] + a[x + 1][3]);//固定y,搜索x
dfs(x, y + 1, t + a[n - y][1] + a[n - y][2]);//固定x,搜索y
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
char c;
cin >> c;
if (c == 'W')
a[i][1]++;
else if (c == 'B')
a[i][2]++;
else if (c == 'R')
a[i][3]++;
}
}
dfs(0, 0, 0);
cout << ans;
return 0;
}