Prefix Sum

该代码实现了一个PrefixSum算法,用于计算数组的前缀和,并处理区间查询。在读取数组长度n和查询次数m后,它计算数组的前缀和,并对每个查询范围(l,r),输出l到r的元素之和。假设数组从1开始索引。
摘要由CSDN通过智能技术生成

prefix and

Enter a sequence of integers of length n. Next, enter m queries, and enter a pair of l, r for each query. For each query, output the sum from the lth number to the rth number in the original sequence.

input format
The first line contains two integers n and m.
The second line contains n integers, representing a sequence of integers.
Next m lines, each line contains two integers l and r, representing a query range.

output format
A total of m lines, each line outputs a query result.

data range
1≤l≤r≤n
1≤n,m≤100000
−1000≤The value of the element in the array≤1000

Input sample:
5 3
2 1 3 6 4
1 2
1 3
twenty four
Sample output:
3
6
10

Solution

This code implements a prefix sum algorithm to calculate the prefix sum of an array q. The prefix sum of an array is the sum of all elements up to a certain index. For example, the prefix sum of the first i elements of an array q is s[i] = q[1] + q[2] + ... + q[i].

The code first reads two integers n and m from standard input, which represent the length of the array q and the number of queries to perform, respectively. It then reads the elements of the array q from standard input using a loop, and calculates the prefix sum s of the array q. Specifically, it uses another loop to iterate over the elements of q, and calculates the prefix sum s by storing the sum of the current element and the previous prefix sum in s[i] = s[i - 1] + q[i].

After calculating the prefix sum, the code enters a loop to perform the queries. In each iteration of the loop, it reads two integers l and r from standard input, which represent the left and right indices of the subarray to query. It then calculates the sum of the subarray by subtracting the prefix sum at index l - 1 from the prefix sum at index r, and outputs the result to standard output.

Note that this code assumes that the array q is 1-indexed. If the array is 0-indexed, the loop that calculates the prefix sum should start at index 0 instead of 1.

#include <bits/stdc++.h>

using namespace std;

const int N = 10010;

int n, m;
int q[N], s[N];

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i ++ ) cin >> q[i];
    for (int i = 1; i <= n; i ++ ) s[i] = s[i - 1] + q[i];
    while (m -- ) {
        int l, r;
        cin >> l >> r;
        cout << s[r] - s[l - 1] << endl;
    }
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值