P3392 涂国旗

深度搜索:

设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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"c洛谷国旗"是一个题目,在洛谷在线评测系统上。该题目的要求是给定一个由N×M个小方块组成的棋盘布,每个方块是白色、蓝色或红色。你需要按照某国法律规定的国旗规则,将布成合法的国旗。根据法律规定,国旗的布局应该是从最上方若干行(至少一行)的格子全部是白色的,接下来若干行(至少一行)的格子全部是蓝色的,剩下的行(至少一行)全部是红色的。你需要通过对格子上颜色的改来实现这个目标。具体来说,你需要在一些格子上上新的颜色来盖住之前的颜色。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [洛谷 P3392 国旗](https://blog.csdn.net/m0_60777643/article/details/122149321)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [洛谷-P3392 国旗](https://blog.csdn.net/weixin_43098069/article/details/107484242)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值