(Three methods) Solve the one-dimensional prefix sum

Title

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.

The next m lines, each line contains two integers l and r, representing the range of a query.

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 sequence ≤1000

Input sample:

5 3
2 1 3 6 4
1 2
1 3
2 4

Sample output:

3
6
10

Method 1: Violent enumeration

#include <iostream>
using namespace std;
const int N=100010;
int main()
{
    
    
    int s[N];
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
    
    
        cin>>s[i];
    }
    
    while(m--)
    {
    
    
        int l,r;
        int sum=0;
        cin>>l>>r;
        for(int i=l;i<=r;i++)
        {
    
    
            sum+=s[i];
        }
       cout<<sum<<endl;
        
    }
    return 0;
    
    
}

Method 2: accumulate function

The accumulate function generally has two uses, one of which is to accumulate array elements.
Usage: accumulate (first pointer, last pointer, accumulate initial value) The
header file is: #include <numeric>

#include <iostream>
#include<numeric>      //注意头文件
using namespace std;
const int N=100010;
int main()
{
    
    
    int s[N];
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
    
    
        cin>>s[i];       //输入序列
    }
    
    while(m--)
    {
    
    
        int l,r;
        cin>>l>>r;
        cout<<accumulate(s+l,s+r+1,0)<<endl;     //直接计算出数列在区间[l,r]的和
    }
    return 0;
    
}

Method three: prefix and algorithm

#include <iostream>
using namespace std;
const int N=100010;
int main()
{
    
    
    int s[N];
    int n,m;
    cin>>n>>m;
    s[0]=0;
    for(int i=1;i<=n;i++)
    {
    
    
        cin>>s[i];
        s[i]=s[i-1]+s[i];    //初始化前缀和数组s[]
    }
    
    while(m--)
    {
    
    
        int l,r;
        cin>>l>>r;
        cout<<s[r]-s[l-1]<<endl;    //利用前缀和算法计算区间[l,r]上的值
        
    }
    return 0;
    
    
}

Guess you like

Origin blog.csdn.net/qq_46009744/article/details/114233574