Frage

i was writing a piece of code where i had to perform a division by 2.The following line of code gives correct output

ans = ans + ((long long)cnt * (cnt-1))/2;

However when I change it to

ans = ans + ((long long)cnt * (cnt-1)) >> 1;

What is wrong in the code above

In my setup the values are never negative

Here is the code

#include<bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
int s[1000000];
int main(){_
int t;
cin>>t;
while(t--){
    int n,i,z,sum=0,p,cnt=0;
    unsigned long long int ans=0;
    cin>>n;
    for(i=0;i<n;i++){
        cin>>z;
        sum+=z;
        s[i]=sum;
    }
    sort(s,s+n);
    i=0;
    while(i<n){
        p=s[i];
        cnt=0;
        while(s[i]==p){
            cnt++;
            i++;
        }
        ans=ans+((unsigned long long)cnt*(cnt-1))>>1;
    }
    cnt=0;
    for(int i=0;i<n && s[i]<=0;i++){
        if(s[i]==0){
            cnt++;
        }
    }
    ans+=cnt;
    cout<<ans<<"\n";
}
return 0;
}

For the input 1 4 0 1 -1 0

The output is 4 however it should be 6

Also the code is giving Sigsegv error for high inputs

1<=t<=5

1<=n<=10^6

-10<= z <= 10

War es hilfreich?

Lösung 2

For the sigsegv problem, I'd guess that it's the result of i index running past the end of the s[] array under certain conditions in the inner loop here:

while(i<n){
       p=s[i];
       cnt=0;
       while(s[i]==p){
           cnt++;
           i++;         // <== I'm not convinced this will always remain less than n
                        //     or less than 1000000 depending on the data set and 
                        //     what happens to be in memory after `s[]`
       }
       ans=ans+((unsigned long long)cnt*(cnt-1))>>1;
}

Andere Tipps

Operator >> has a lower precedence than + (and of course /), hence you wrote the equivalent of:

ans = ( ans + ((long long)cnt * (cnt-1)) ) >> 1;
//    ^--- note these -------------------^
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top