首页 > 解决方案 > 为什么当我从语句检查中删除“+ mod”时以下程序给出错误答案。问题链接:https://www.codechef.com/problems/FFC219B

问题描述

语句检查是我不明白为什么当我写“sum = (solution[R]-solution[L-1])%mod;”时它在提交时显示错误答案的地方 反而。这里我没有在括号内添加mod。我看不出答案是如何通过添加相同的模式来改变的。codechef 中的问题代码:https ://www.codechef.com/problems/FFC219B

#include<iostream>
#define ll long long
#define mod 1000000007   //the modulus we need to take for the final answer
#define endl "\n"
using namespace std;

long long solution[100007] = {0}; //Initialising all the values with zero

int main(){

ios_base :: sync_with_stdio(0);

cin.tie(0);

cout.tie(0);

solution[0] = 0;

ll a1=1,a2=2,a3=3,a4=4;    //The variable initialising as per the problem

 for(int i = 1;i <= 100007;i++){

     ll k=(a1 * a2) % mod * a3 % mod * a4 % mod;

        solution[i] = (solution[i-1]+k)%mod;  //Adding the previous values as we are to find the sum in range

        a1++;

        a2++;

        a3++;

        a4++;
     }

    int t; //Taking input for number of test cases

    cin>>t;

    while(t-->0)
    {

        int L,R;

        cin>>L>>R; //Taking the range input

        long long sum = 0;

        sum = (solution[R]-solution[L-1] + mod)%mod; //statement check & final answer

        cout<<sum<<endl;

       }
    return 0;
}

标签: c++

解决方案


该程序可能会给出错误答案,因为正确答案必须始终是正数,而不是负数。

当您减去连续的模值时,即使数字本身正在增加,结果也可能是负数(例如,(4^3)%10 - (4^2)%10 = 64%10 - 16%10 = 4-6 = -2), . 这意味着“solution[R]-solution[L-1]”也可能是负数,这意味着“(solution[R]-solution[L-1]) % mod”也将是负数——尽管答案很明显 (受影响的人数)必须始终为正数。

因此,以这种方式添加 mod 值可确保结果始终为正。


推荐阅读