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

AC code:

#include<stdio.h>

int n,m;
int a[100010];

int figure(int l,int r)
{
    
    
    return a[r]-a[l-1];
}

int main()
{
    
    
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;++i)
    {
    
    
        scanf("%d",&a[i]);
        a[i]+=a[i-1];//读数据时顺便加工成前缀和
    }
    for(int i=0;i<m;++i)
    {
    
    
        int l,r;
        scanf("%d%d",&l,&r);
        printf("%d\n",figure(l,r));
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108768485
Recommended