AcWing 795. Prefix and [c++ detailed solution]

Prefix and


topic

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 row contains n integers, representing a sequence of integers.

In 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 elements in the sequence ≤1000
Input example:
5 3
2 1 3 6 4
1 2
1 3
2 4
Output example:
3
6
10

specific methods:

First do a preprocessing, define an sum[]array, which sum[i]represents the sum aof the previous inumbers in the array .

Find the prefix and operation:

const int N=1e5+10;
int sum[N],a[N]; //sum[i]=a[1]+a[2]+a[3].....a[i];
for(int i=1;i<=n;i++)
{
    
     
    sum[i]=sum[i-1]+a[i];   
}

Then query operation:

 scanf("%d%d",&l,&r);
 printf("%d\n", sum[r]-sum[l-1]);

For each query, only need to execute sum[r]-sum[l-1], the time complexity isO(1)

principle

sum[r] =a[1]+a[2]+a[3]+a[l-1]+a[l]+a[l+1]......a[r];
sum[l-1]=a[1]+a[2]+a[3]+a[l-1];
sum[r]-sum[l-1]=a[l]+a[l+1]+......+a[r];

Illustrates
Insert picture description here
Thus, for each 只需要执行 sum[r]-sum[l-1]inquiry . lThe time complexity of outputting the sum from the number to the rth number in the original sequence becomes O(1).

We call it a one-dimensional prefix sum .

to sum up:

Summary of personal experience of prefix sum and difference

AC code

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

Guess you like

Origin blog.csdn.net/weixin_45629285/article/details/111592623