c++ - 使用 INT32_MAX 时无法打印正确答案
问题描述
我试图解决一个DP问题。因为我需要将一个值设置为一个大数字,所以我使用了 INT32_MAX。当我使用 INT32_MAX 时,我的代码返回 -2147483647。但是,如果我将 INT32_MAX 更改为 INF(const int INF = 987654321;) 它可以工作。为什么使用 INT32_MAX 无法收到正确答案?当我尝试使用 INT32_MAX 时,我将每个 INF 值更改为 INT32_MAX。以下是我的代码:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int IDX = 110;
const int INF = 987654321;
int maze_size, maze[IDX], cache[IDX];
int JumpToNext(int curr_loc){
if(curr_loc == maze_size) return 0;
if(curr_loc > maze_size) return INF;
int & now = cache[curr_loc];
if(now != -1) return now;
now = INF;
for(int next = 1; next <= maze[curr_loc]; next++){
now = min(now, JumpToNext(curr_loc + next) + 1);
}
return now;
}
int main(void){
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> maze_size;
memset(cache, -1, sizeof(cache));
for(int m = 1; m <= maze_size; m++) cin >> maze[m];
int ans = JumpToNext(1);
ans == INF ? cout << -1 : cout << ans;
}
测试用例:
10
1 2 0 1 3 2 1 5 4 2
正确答案:
5
解决方案
Does JumpToNext
ever return INT32_MAX
? Because INT32_MAX + 1 == INT32_MIN == -2147483647
.
推荐阅读
- angular - nyc + cypress + angular 前缀为 webpack:?
- forms - 如何在 Xamarin 中将 DPI 设备获取到 PCL。形式?- 跟进
- blockchain - 如何将TRON地址转换为不同的格式
- python - 如何从不同目录导入两个文件?
- java - Outlook Web Client 上不显示小图像以外的内嵌图像
- python - 如何在 Python 中更新字典列表中的键
- vba - 我无法操作变体数组
- git - 忽略子模块内的 Git 子模块
- c++ - 错误:命名空间“cv::cuda”没有成员“resize”
- c++ - 使用 _beginthreadex、__stdcall 和 lambda 创建线程