【记忆化搜索】【剪枝】【C++算法】1553吃掉 N 个橘子的最少天数

作者推荐

【数位dp】【动态规划】【状态压缩】【推荐】1012. 至少有 1 位重复的数字

涉及知识点

记忆化搜索 剪枝 分类讨论

LeetCode1553. 吃掉 N 个橘子的最少天数

厨房里总共有 n 个橘子,你决定每一天选择如下方式之一吃这些橘子:
吃掉一个橘子。
如果剩余橘子数 n 能被 2 整除,那么你可以吃掉 n/2 个橘子。
如果剩余橘子数 n 能被 3 整除,那么你可以吃掉 2*(n/3) 个橘子。
每天你只能从以上 3 种方案中选择一种方案。
请你返回吃掉所有 n 个橘子的最少天数。
示例 1:
输入:n = 10
输出:4
解释:你总共有 10 个橘子。
第 1 天:吃 1 个橘子,剩余橘子数 10 - 1 = 9。
第 2 天:吃 6 个橘子,剩余橘子数 9 - 2*(9/3) = 9 - 6 = 3。(9 可以被 3 整除)
第 3 天:吃 2 个橘子,剩余橘子数 3 - 2*(3/3) = 3 - 2 = 1。
第 4 天:吃掉最后 1 个橘子,剩余橘子数 1 - 1 = 0。
你需要至少 4 天吃掉 10 个橘子。
示例 2:
输入:n = 6
输出:3
解释:你总共有 6 个橘子。
第 1 天:吃 3 个橘子,剩余橘子数 6 - 6/2 = 6 - 3 = 3。(6 可以被 2 整除)
第 2 天:吃 2 个橘子,剩余橘子数 3 - 2*(3/3) = 3 - 2 = 1。(3 可以被 3 整除)
第 3 天:吃掉剩余 1 个橘子,剩余橘子数 1 - 1 = 0。
你至少需要 3 天吃掉 6 个橘子。
示例 3:
输入:n = 1
输出:1
示例 4:
输入:n = 56
输出:6
提示:
1 <= n <= 2*109

分类讨论

具有如下性质:
性质一:如果n>=3,则不可能全部是方案一,必定有方案二或方案三。当只有三个桔子时,采用方案三,只需要2天;全部全部使用方案一,则需要3天。
性质二:如 n>=4 ,且没有使用方案三或先使用方案二。则必定在n/2 × \times × 2处采用方案二。反证法:假定某一方案,在j2个桔子时,首先使用方案二,j < n/2 假定一 。 n → \rightarrow n/2 × \times × 2 和j → \rightarrow 0完全一样,所以只讨论:n/2 × \times × 2 → \rightarrow j。
n/2 × \times × 2 → \rightarrow n/2 → \rightarrow j ,最多用了:1+ (n/2) - j 天。式子一
n/2 × \times × 2 → \rightarrow 2j → \rightarrow j 用了 n-2
j+1 = n/2-j+ 1+(n/2)-j 式子二
式子二减去式子一:n/2- j 根据假定一,大于0。故:必定在n/22处采用方案二。
性质三:如果n >=6。且没有使用方案二或先使用方案三,则必定n/3
3出采用方案三。证明类似。

代码

核心代码

class Solution {
public:
	int minDays(int n) {
		m_data[1] = 1;
		m_data[2] = 2;
		m_data[3] = 2;
		return Rec(n);
	}
	int Rec(int n)
	{
		if (m_data.count(n))
		{
			return m_data[n];
		}
		return m_data[n] = min(Rec(n / 2 ) +n %2 +1 , Rec(n / 3)+  1 +  n %3 );
	}
	unordered_map<int, int> m_data;
};

测试用例

template<class T>
void Assert(const T& t1, const T& t2)
{
	assert(t1 == t2);
}

template<class T>
void Assert(const vector<T>& v1, const vector<T>& v2)
{
	if (v1.size() != v2.size())
	{
		assert(false);
		return;
	}
	for (int i = 0; i < v1.size(); i++)
	{
		Assert(v1[i], v2[i]);
	}

}

int main()
{	
	
	{
		Solution sln;
		vector<int> in = { 1,2,3,4,5,6,10,2000000000 };
		vector<int> ans = { 1,2,2,3,4,3 ,4,32};
		vector<int> res(in.size());
		for (int i = 0; i < in.size(); i++)
		{
			res[i] = sln.minDays(in[i]);
		}
		Assert(res, ans);
	}

}

2023年2月

class Solution {
public:
int minDays(int n) {
if( n < 3 )
{
return n ;
}
return min( n%3 + minDays(n/3) +1 ,n%2 + minDays(n/2)+1);
}
};

2023年2月 第二版

class Solution {
public:
int minDays(int n) {
if( n < 3 )
{
return n ;
}
auto it = m_mNValue.find(n);
if( m_mNValue.end() !=it )
{
return it->second;
}
return m_mNValue[n] = min( n%3 + minDays(n/3) +1 ,n%2 + minDays(n/2)+1);
}
std::unordered_map<int,int> m_mNValue;
};

2023年7月

class Solution {
public:
int minDays(int n)
{
if (n < 3)
{
return n;
}
if (m_result.count(n))
{
return m_result[n];
}
int iRet3 = (0 == n % 3) ? (minDays(n / 3) + 1) : (minDays(n / 3 * 3) + n % 3);
int iRet2 = (0 == n % 2) ? (minDays(n / 2) + 1) : (minDays(n / 2 * 2) + n % 2);
return m_result[n] = min(iRet3, iRet2);
}
std::unordered_map<int, int> m_result;
};

2023年9月

class Solution {
public:
int minDays(int n) {
if (n < 3)
{
return n;
}
if (m_mRes.count(n))
{
return m_mRes[n];
}
int iRet = min(minDays(n / 3) + 1 + n % 3, minDays(n / 2) + 1 + n % 2);
return m_mRes[n] = iRet;
}
std::unordered_map<int, int> m_mRes;
};

扩展阅读

视频课程

有效学习:明确的目标 及时的反馈 拉伸区(难度合适),可以先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
https://edu.csdn.net/course/detail/38771

如何你想快

速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
https://edu.csdn.net/lecturer/6176

相关

下载

想高屋建瓴的学习算法,请下载《喜缺全书算法册》doc版
https://download.csdn.net/download/he_zhidan/88348653

我想对大家说的话
闻缺陷则喜是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。
子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。
如果程序是一条龙,那算法就是他的是睛

测试环境

操作系统:win7 开发环境: VS2019 C++17
或者 操作系统:win10 开发环境: VS2022 **C+

+17**
如无特殊说明,本算法用**C++**实现。

  • 14
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,这里是一个用 C++ 实现的五子棋 AI,使用了 Alpha-Beta 剪枝算法: ```c++ #include <iostream> #include <vector> #include <algorithm> using namespace std; const int BOARD_SIZE = 15; // 棋盘大小 const int MAX_DEPTH = 3; // 最大搜索深度 const int WIN_SCORE = 1000000; // 获胜得分 const int INF = 0x3f3f3f3f; // 无穷大 int board[BOARD_SIZE][BOARD_SIZE]; // 棋盘 int player; // 玩家 int ai; // AI // 判断是否越界 bool isInRange(int x, int y) { return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE; } // 判断是否为空位 bool isEmpty(int x, int y) { return board[x][y] == 0; } // 判断是否为玩家棋子 bool isPlayer(int x, int y) { return board[x][y] == player; } // 判断是否为 AI 棋子 bool isAI(int x, int y) { return board[x][y] == ai; } // 在 (x,y) 处落子 void move(int x, int y, int chess) { board[x][y] = chess; } // 悔棋 void unmove(int x, int y) { board[x][y] = 0; } // 检查是否五子连珠 bool checkWin(int x, int y) { int dx[4] = {0, 1, 1, 1}; // 横、竖、斜1、斜2 int dy[4] = {1, 0, 1, -1}; for(int i = 0; i < 4; i++) { int cnt = 1; for(int j = 1; j <= 4; j++) { int nx = x + j * dx[i], ny = y + j * dy[i]; if(isInRange(nx, ny) && isAI(nx, ny)) cnt++; else break; } for(int j = 1; j <= 4; j++) { int nx = x - j * dx[i], ny = y - j * dy[i]; if(isInRange(nx, ny) && isAI(nx, ny)) cnt++; else break; } if(cnt >= 5) return true; } return false; } // 评估函数 int evaluate() { int score = 0; // 统计每个空位的得分 for(int i = 0; i < BOARD_SIZE; i++) { for(int j = 0; j < BOARD_SIZE; j++) { if(isEmpty(i, j)) { int cnt1 = 0, cnt2 = 0; int dx[4] = {0, 1, 1, 1}; // 横、竖、斜1、斜2 int dy[4] = {1, 0, 1, -1}; for(int k = 0; k < 4; k++) { int cnt = 1; for(int l = 1; l <= 4; l++) { int nx = i + l * dx[k], ny = j + l * dy[k]; if(isInRange(nx, ny) && isAI(nx, ny)) cnt++; else break; } for(int l = 1; l <= 4; l++) { int nx = i - l * dx[k], ny = j - l * dy[k]; if(isInRange(nx, ny) && isAI(nx, ny)) cnt++; else break; } if(cnt >= 5) cnt1++; else if(cnt == 4) cnt2++; } score += cnt1 * WIN_SCORE + cnt2 * (WIN_SCORE / 10); } } } return score; } // Alpha-Beta 剪枝搜索 int alphabeta(int depth, int alpha, int beta) { if(depth == 0) return evaluate(); // 叶节点,返回评估值 vector<pair<int, int>> moves; // 当前局面下所有可行的落子位置 for(int i = 0; i < BOARD_SIZE; i++) { for(int j = 0; j < BOARD_SIZE; j++) { if(isEmpty(i, j)) moves.push_back({i, j}); } } if(moves.empty()) return 0; // 没有可行的落子位置,返回 0 // 对可行的落子位置进行排序,以加速剪枝 sort(moves.begin(), moves.end(), [](const pair<int, int>& a, const pair<int, int>& b) { return evaluate() > evaluate(); }); int bestScore = -INF; // 最佳得分 for(const auto& move : moves) { int x = move.first, y = move.second; move(x, y, ai); // AI 落子 int score = -alphabeta(depth - 1, -beta, -alpha); // 对手的最佳反应是当前局面的最大负值 unmove(x, y); // 悔棋 if(score >= beta) return score; // Beta 剪枝 if(score > bestScore) { // 更新最佳得分和 Alpha 值 bestScore = score; if(score > alpha) alpha = score; } } return bestScore; } // AI 落子 void AIMove() { vector<pair<int, int>> moves; // 当前局面下所有可行的落子位置 for(int i = 0; i < BOARD_SIZE; i++) { for(int j = 0; j < BOARD_SIZE; j++) { if(isEmpty(i, j)) moves.push_back({i, j}); } } if(moves.empty()) return; // 没有可行的落子位置,直接返回 int bestScore = -INF; // 最佳得分 pair<int, int> bestMove; // 最佳落子位置 // 对可行的落子位置进行排序,以加速搜索 sort(moves.begin(), moves.end(), [](const pair<int, int>& a, const pair<int, int>& b) { return evaluate() > evaluate(); }); // 搜索最佳落子位置 for(const auto& move : moves) { int x = move.first, y = move.second; move(x, y, ai); // AI 落子 int score = -alphabeta(MAX_DEPTH - 1, -INF, INF); // 对手的最佳反应是当前局面的最大负值 unmove(x, y); // 悔棋 if(score > bestScore) { // 更新最佳得分和最佳落子位置 bestScore = score; bestMove = move; } } move(bestMove.first, bestMove.second, ai); // AI 落子 cout << "AI moves: (" << bestMove.first << ", " << bestMove.second << ")" << endl; } // 玩家落子 void playerMove() { int x, y; while(true) { cout << "Please enter your move (x y): "; cin >> x >> y; if(isInRange(x, y) && isEmpty(x, y)) break; else cout << "Invalid move, please try again." << endl; } move(x, y, player); // 玩家落子 } // 打印棋盘 void printBoard() { cout << " "; for(int i = 0; i < BOARD_SIZE; i++) { cout << i << " "; } cout << endl; for(int i = 0; i < BOARD_SIZE; i++) { cout << i << " "; for(int j = 0; j < BOARD_SIZE; j++) { if(isEmpty(i, j)) cout << "+ "; else if(isPlayer(i, j)) cout << "O "; else cout << "X "; } cout << endl; } } int main() { // 初始 for(int i = 0; i < BOARD_SIZE; i++) { for(int j = 0; j < BOARD_SIZE; j++) { board[i][j] = 0; } } player = 1; ai = 2; // 开始游戏 while(true) { printBoard(); playerMove(); if(checkWin(player)) { cout << "You win!" << endl; break; } AIMove(); if(checkWin(ai)) { cout << "AI wins!" << endl; break; } } return 0; } ``` 这个五子棋 AI 使用 Alpha-Beta 剪枝算法进行搜索,评估函数采用了一种简单的方法,即统计每个空位的得分,得分越高的空位越有可能是最佳落子位置。这个 AI 的搜索深度可以通过修改 `MAX_DEPTH` 来调整,可以根据自己的需求进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闻缺陷则喜何志丹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值