Rafsan's blog

By Rafsan, 11 years ago, In English

Following code shows correct output in my CodeBlocks::10.05 but, in CODEFORCES CUSTOM TEST it shows incorrect output.

Main problem is that, in calculation block the value of sum is initialized to 0 in each iteration.

After long experiment I found that
- if I change line 19: form sum+=(i-1)*arr[i]-prevsum; to sum=sum+(i-1)*arr[i]-prevsum; then it shows correct result.
- Or,if I declare array as int instead of long long then it shows correct result.

But I can not able to figure out "why value of sum is becoming 0 in each iteration??". Somebody please help me..

#include<iostream>
#include<cstdio>
#define LL long long
using namespace std;
LL arr[100005];
int main()
{
    int n;
    cin>>n;
    LL sum=0,prevsum=0;
    for(int i=1;i<=n;i++)
    {
       cin>>arr[i];
    }
//calculation block starts here
    for(int i=1;i<=n;i++)
    {
    cout<<"sum : "<<sum<<endl;
    sum+=(i-1)*arr[i]-prevsum;
    prevsum+=arr[i];
    }
//calculation block ends here
    cout<<"Final Result: "<<sum<<endl;

    return 0;
}
/*
Input : 
5
1 2 3 4 5
*/

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
11 years ago, # |
  Vote: I like it +5 Vote: I do not like it

It's a bug of GNU C++ 4.7.2.

  • »
    »
    11 years ago, # ^ |
      Vote: I like it +2 Vote: I do not like it

    is it same for other OJ like TopCoder, Spoj, Uva ?? What are suggestions to avoid this types of weird bug??

    • »
      »
      »
      11 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      Almost all versions of GNU C++ don't have this bug (at least 4.8.1 doesn't have).

      How to avoid? Maybe use Visual Studio Compiler?

      • »
        »
        »
        »
        11 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        I tried 4.8.1 and the code produced the same incorrect output 0.

»
11 years ago, # |
  Vote: I like it +16 Vote: I do not like it
  • »
    »
    11 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    Is the same compiler version & options used in CF Rounds? If it is, is there any way we can do to avoid this? (Changing compiler doesn't look like a good options for those who doesn't have other compilers & have codes that depend on compiler.)

    • »
      »
      »
      11 years ago, # ^ |
      Rev. 2   Vote: I like it +6 Vote: I do not like it

      You can try to add

      #pragma GCC optimize("O0")

      at the beginning of your program to disable optimization. But, of course, this will make your program a lot slower.

      If in the above bug report the GCC developers find a particular optimizer option that is causing this, then you can use the optimize pragma to disable only this option.