fork download
  1. # your code goes here
  2. import sys
  3.  
  4. def solve():
  5. # Fast I/O
  6. input = sys.stdin.read
  7. data = input().split()
  8.  
  9. if not data:
  10. return
  11.  
  12. # Parse N and the list of numbers
  13. N = int(data[0])
  14. numbers = [int(x) for x in data[1:N+1]]
  15.  
  16. # Parse Q
  17. Q = int(data[N+1])
  18.  
  19. # Step 1: Build the prefix sum array
  20. pref = [0] * N
  21. pref[0] = numbers[0]
  22. for k in range(1, N):
  23. pref[k] = pref[k-1] + numbers[k]
  24.  
  25. # Step 2: Process each query
  26. # Queries start at index N + 2 in the flattened data array
  27. query_idx = N + 2
  28. output = []
  29.  
  30. for _ in range(Q):
  31. i = int(data[query_idx])
  32. j = int(data[query_idx+1])
  33. query_idx += 2
  34.  
  35. # Ensure i is the smaller index if they are given out of order
  36. if i > j:
  37. i, j = j, i
  38.  
  39. # O(1) Range Sum Calculation
  40. if i == 0:
  41. output.append(str(pref[j]))
  42. else:
  43. output.append(str(pref[j] - pref[i-1]))
  44.  
  45. # Print all answers separated by a newline
  46. sys.stdout.write('\n'.join(output) + '\n')
  47.  
  48. if __name__ == '__main__':
  49. solve()
  50.  
Success #stdin #stdout 0.07s 13984KB
stdin
Standard input is empty
stdout
Standard output is empty