-3

I have an array of n elements unsorted,now a query q comes in a form of l,r,t where l<=r are indices of array and we have to find sum from l to r in a subarray where each element must be less than or equal to t.

n<=10^5

q<=10^5

ai(element of an array)<=10^5

t<=10^5

what is the most efficient data structure to solve this problem ?

Yash Jain
  • 1
  • 1
  • what you have done so far ? – Om Sao Jul 14 '17 at 17:45
  • Probably a `std:: vector`. – user4581301 Jul 14 '17 at 17:45
  • tried using merge sort tree,but complexity is still high – Yash Jain Jul 14 '17 at 17:46
  • francois ,sorry it was supposed to be t – Yash Jain Jul 14 '17 at 17:47
  • 1
    Possible duplicate of [How to effectively answer range queries in an array of integers?](https://stackoverflow.com/questions/45095057/how-to-effectively-answer-range-queries-in-an-array-of-integers) – Nico Schertler Jul 14 '17 at 17:47
  • Can you modify your array? If so, consider using [`std::remove_if`](http://en.cppreference.com/w/cpp/algorithm/remove) to eliminate the values above `t` and then sum all elements in the requested range. Otherwise, just iterate and count if the value is no more than `t`? – François Andrieux Jul 14 '17 at 17:48
  • Francois i think that cant work because i want complexity in logarithmic range – Yash Jain Jul 14 '17 at 17:53
  • For each array there may be more than one query? – user4581301 Jul 14 '17 at 18:14
  • You need to create a segment tree. Take values less than t while creating the segment tree. – CodeHunter Jul 14 '17 at 18:35
  • *Show an example* Give us a sample array, a couple of sample queries, and the expected outputs. With the addition of the `t` restriction, it seems like the best you can do is O(n): sum all of the items from l to r. And by the way, your explanation says that "q <= 10^5", which doesn't make a lot of sense. Is that supposed to mean that the range (i.e. `r-l`) will be less than 10^5? – Jim Mischel Jul 14 '17 at 20:53
  • let an array be like {7,6,14,8,10} now let q=3 – Yash Jain Jul 15 '17 at 04:29
  • let an array be like {7,6,14,8,10} now let q=3, (l=1,r=2,t=6,output=6),(l=2,r=4,t=8,output=14),(l=1,r=5,t=9,output=21). – Yash Jain Jul 15 '17 at 04:34

1 Answers1

0

Most efficient data structure is sparse table ( O(nlogn) time to built and O(1) time to query ) or segment tree (O(n) time to built & O(logn) time to query ).