Range Sum Queries Per Testcase
Python
Medium
5 views
Problem Description
Each testcase has n numbers and q queries (l r, 1-based). Output sum for each query.
Input Format
First integer t. For each: n q, then n ints, then q lines l r.
Output Format
For each testcase, q lines sums.
Sample Test Case
Input:
1
5 3
1 2 3 4 5
1 3
2 5
4 4
Constraints
Sum of n+q over all testcases
Official Solution
import sys
data=sys.stdin.read().strip().split()
if not data:
sys.exit(0)
it=iter(data)
t=int(next(it))
out=[]
for tc in range(t):
n=int(next(it)); q=int(next(it))
a=[int(next(it)) for _ in range(n)]
pref=[0]*(n+1)
for i,v in enumerate(a):
pref[i+1]=pref[i]+v
for _ in range(q):
l=int(next(it)); r=int(next(it))
out.append(str(pref[r]-pref[l-1]))
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!