Is there any optimal solution (better than O(n^2) to count sub-arrays have non-negative sum?

Правка en1, от mimi301208, 2024-02-25 14:10:06

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]);
    }
Теги algo

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский mimi301208 2024-02-25 14:10:06 721 Initial revision (published)