首页 > 解决方案 > 使用 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

标签: c++

解决方案


Does JumpToNext ever return INT32_MAX? Because INT32_MAX + 1 == INT32_MIN == -2147483647.


推荐阅读