I am solving a problem which states the following: There is a row of buckets numbered from 1 to n. A gardener fills this buckets in a particular fashion. He fills the buckets between two ends l and r including l and r with 1<=l<=r<=n. He does this for k times. We need to find the bucket which is having water equal to the median of volumes in the buckets. I am using a program of time complexity knlgn to solve this. The input is like this: the first line contain n and k seperated by spaces and the next k lines contain pairs l and r for each watering process. I am using an algorithm of nklgn to solve this as follows:
while True:
nk = input().split(' ')
n = int(nk[0])
k = int(nk[1])
a = input().split(' ')
for z in range(len(a)):
a[z] = int(a[z])
if n==0 and k==0: break
for mn in range(k):
(x, y) = input().split(' ')
x = int(x)-1
y = int(y)-1
for z in range(x, y+1):
a[z] += 1
print(sorted(a)[int(len(a)/2)])
Please help me solve this using a better algorithm and I have encountered a very similar problem at least 3 to 4 times. You may give me some hint in the answer if not entire code.
I think you should make use of Segment Tree . This data structure is used to update and retrieve a particular query in O(log(n)) time.
You can update the tree in the following way: first find the nodes which covers the range [l, r] and then store the updated value in those nodes. Process all the queries like this - storing the updated value only in the top node without changing the original nodes. After this, in a pre-order traversal you can update all the necessary nodes in O(n) time. I think this will be a pretty reasonable optimisation.
If you are not aware of this data structure, then I recommend you to first read about it and then try to understand my answer.
首先,在最后一行中,当您只需要一个元素时,就不需要对列表进行完整的排序。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.