gpt4 book ai didi

c++ - 使用INT32_MAX时无法打印正确答案

转载 作者:行者123 更新时间:2023-12-02 10:03:15 27 4
gpt4 key购买 nike

我试图解决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

最佳答案

JumpToNext是否会返回INT32_MAX吗?因为INT32_MAX + 1 == INT32_MIN == -2147483647

关于c++ - 使用INT32_MAX时无法打印正确答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61500272/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com