School Enrollment Exercise 030 Harvest (Netease)

Keywords: PHP

Have bumper harvest

Title Description
It's harvest time again. It's time for Xiaoyi to go to Niuniu's orchard.
Niuniu often said that he knew every part of the orchard like his palm. Xiaoyi didn't believe it very much, so he wanted to test Niuniu.
There are N piles of apples in the orchard. The number of apples in each pile is ai. Xiaoyi hopes to know which pile the Xth apple from left to right belongs to.
Niuniu thinks this question is too simple, so I hope you can answer it for him.

Input Description:
The number n of the first line (1 < = n < = 105).
The number of AI (1 <= AI <== 1000) i n the second row indicates how many apples are in the pile I from left to right.
The third line has a number m (1 <= m <= 105), indicating that there are m queries.
The fourth line, the number of m qi, indicates that Xiaoyi wishes to know which pile the qi Apple belongs to.

Output description:
Line m, line i outputs which stack the qi th Apple belongs to.

 1 def main():
 2     N = int(input())
 3     apples = list(map(int,input().split()))
 4     # N = 5
 5     # apples = [2,7,3,4,9]
 6 
 7     apples.insert(0,0)
 8     for i in range(1,N+1):
 9         apples[i] += apples[i-1]
10     
11     M = int(input())
12     questions = list(map(int,input().split()))
13     # print(apples)
14     # M = 3
15     # questions = [1,25,11]
16     for i in range(M):
17         cur = questions[i]
18         l,r = 0,N
19         while l <= r:
20             m = l + (r - l) // 2
21             if cur == apples[m]:
22                 print(m)
23                 break
24             elif cur < apples[m]:
25                 if m - 1 >= 0 and cur > apples[m-1]:
26                     print(m)
27                     break
28                 else:
29                     r = m - 1
30             elif cur > apples[m]:
31                 if m + 1 <= N and cur < apples[m+1]:
32                     print(m+1)
33                     break
34                 else:
35                     l = m + 1
36             else:
37                 print('error')
38 
39 if __name__ == '__main__':
40     main()

Algorithmic Ideas: Binary Search (Deformation)

Find the right boundary value in an ordered array. You can use the itertools.accumulate() and bisect.bisect_left() methods to simplify the code.

Posted by dhorn on Fri, 11 Oct 2019 12:14:00 -0700