【问题标题】:Integer-Overflow for values upto pow(10,19)高达 pow(10,19) 的值的整数溢出
【发布时间】:2020-07-03 19:33:31
【问题描述】:

这是我正在处理的代码,我遇到了溢出问题。

我的问题中指定的约束是 (0 ≤ v, c, n, m ≤ pow(10,18))

我的代码在此测试用例中失败:63434583954291753 66777666160449180 94688604155374928 61081164840594246

附:我的代码的实现没有问题。只是想避免溢出。 :)。我尝试使用 mod=pow(10,19)+7 和 unsigned long long 来避免溢出。仍然;它不起作用。

#include<iostream>
#include<cmath>
using namespace std;

bool helper(unsigned long long int v,unsigned long long int c,unsigned long long int n,unsigned long long int m,int **output){
    if(n==0 && m==0)
        return true;
    if(n==0){
        if(v > c){
            if(m <= c)
                return true;
            else
                return false;
        }
        else{
            if(m <= v){
                return true;
            }else
                return false;
        }
    }
    if(m==0){
        if(v > c){
            if(n <= v)
                return true;
            else
                return false;
        }
        else{
            if(n <= c){
                return true;
            }else
                return false;
        }
    }
    if(output[n][m]!= -1)
        return output[n][m];
    bool choice1=false;
    bool choice2=false;
    if(v > c){
        if(v>=1)
            choice1=helper(v-1,c,n-1,m,output);
        else
            choice1=false;
    }
    else{
        if(c>=1)
            choice1=helper(v,c-1,n-1,m,output);
        else
            choice1=false;
    }
    if(v > c){
        if(c>=1)
            choice2=helper(v,c-1,n,m-1,output);
        else
            choice2=false;
    }
    else{
        if(v>=1)
            choice2=helper(v-1,c,n,m-1,output);
        else
            choice2=false;
    }
    bool ans=choice1||choice2;
    if(ans)
        output[n][m]=1;
    else
        output[n][m]=0;
    return output[n][m];
}

int main(){
    int t;cin>>t;
    unsigned long long int mod=pow(10,19)+9;
    while(t--){
        unsigned long long int v,c,n,m;
        cin>>v>>c>>n>>m;
        int **output=new int*[(n+1)%mod];
        for(unsigned long long int i=0;i<(n+1)%mod;i++){
            output[i]=new int[(m+1)%mod];
            for(unsigned long long int j=0;j<(m+1)%mod;j++)
                output[i][j]= -1;
        }
        bool ans=helper(v%mod,c%mod,n%mod,m%mod,output);
        if(ans==1)
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
    return 0;
}

【问题讨论】:

    标签: c++ c++11 constraints integer-overflow


    【解决方案1】:

    您输入了 n = 94,688,604,155,374,928。 然后在一行

    int **output=new int*[(n+1)%mod]
    

    这意味着您要求系统分配 n 个整数指针的内存。假设您的操作系统是 64 位,这大约是 90,000 * 8 TB 的内存。我怀疑你的电脑有那么多内存。

    使用较小的数字,不要使用这些非常大的值。

    【讨论】:

    • 哇多少内存??很可笑?? **是做什么的???
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2019-11-07
    • 2016-02-14
    • 2021-02-14
    相关资源
    最近更新 更多