Блог пользователя mimi301208

Автор mimi301208, история, 5 месяцев назад, По-английски

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]);
    }
  • Проголосовать: нравится
  • +15
  • Проголосовать: не нравится

»
5 месяцев назад, # |
  Проголосовать: нравится +6 Проголосовать: не нравится

You can do the same thing with an ordered set, and it improves "distance" (linear) to logarithmic.