Is there any optimal solution (better than O(n^2) to count sub-arrays have non-negative sum?
I've try by using prefix sum and set to count the number of the subarray but it takes lots of time because time complexity of distance function is linear:
multiset <long long> a
for(int i=1;i<=n;++i)
{
cin>>tmp;
sum[i]=sum[i-1]+tmp;
}
ll ans=0;
for(int i=1;i<=n;++i)
{
if(a.size()>0)
{
auto it = a.upper_bound(sum[i]);
ans+=(distance(a.begin(),it;
}
if(sum[i]>=0) ++ans;
a.insert(sum[i]);
}
You can do the same thing with an ordered set, and it improves "distance" (linear) to logarithmic.
thanks so much, it is very helpful