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
*/
It's a bug of GNU C++ 4.7.2.
is it same for other OJ like TopCoder, Spoj, Uva ?? What are suggestions to avoid this types of weird bug??
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?
I tried 4.8.1 and the code produced the same incorrect output 0.
I've posted a bug into gcc bugtracker.
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.)
You can try to add
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.