c++ - 在 spoj AP2 上得到错误答案

标签 c++ optimization

我正在解决一个问题 SPOJ AP2

您将获得第 3 项、第 3 项和系列的总和。您需要系列和系列的打印长度。

使用的逻辑->第一项+最后一项=第三项+倒数第三项

sum=n/2(first+last)

我尝试了很多测试用例,我在所有测试用例中都得到了正确的输出 但是在 spoj 上我得到了错误的答案“WA”

    #include<iostream>
    using namespace std;
    int main(){
        int t;
        cin>>t;
        while(t--){
            long long int third;
            long long int thirdlast;
            long long int sum;
            cin>>third>>thirdlast>>sum;
            long long int n=(2*sum)/(third+thirdlast);
            long long int d= (thirdlast-third)/(n-5);  //(2*thirdlast-third*n+3*third)/(5-n);
            long long int a=(third-2*d);
            //cout<<n<<endl;
            //cout<<d<<endl;
            //int d=0;
            for(int i=1;i<=n;i++){
                long long int temp=d*(i-1);
              //  int t=a+d;
                cout<<a+temp<<" ";


            }
            cout<<endl;

        }
    }

最佳答案

你可能在这一行溢出了:

n=(2*sum)/(third + thirdlast);

您可以通过这种方式避免溢出:

n = 2 * (sum/(third + thirdlast));

但是,由于third + thirdlast可能不能除sum,你必须测试它并在必要时添加n++

另一种解决方案是对n

使用unsigned long long

关于c++ - 在 spoj AP2 上得到错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126838/

相关文章:

c++ - 将 mat vector 转换为 Mat 文件以便使用 opencv svm

c++ - 错误 'TempSLLNODE' : use of class template requires template argument list

optimization - 在什么情况下,AVX2收集指令比单独加载数据要快?

mysql - 如何使用 LIMIT 优化 WHERE 子句中的通配符查询

apache-flex - 无需调试即可编译 Flex 应用程序? flex 编译器的优化选项?

c++ - 将 C++ vector 初始化为随机值...快速

c++ - Undefined reference to function错误,一起使用C和C++

c++ - 在基于范围内自动传递的参数

c++ - 如何帮助编译器根据输入的约束优化我的程序?

c++ - 尝试使用 DDX_CONTROL 连接控件时出错