【模板】前缀和

原题链接:登录---专业IT笔试面试备考平台_牛客网

目录

[1. 题目描述](#1. 题目描述)

[2. 思路分析](#2. 思路分析)

[3. 代码实现](#3. 代码实现)


1. 题目描述

2. 思路分析

前缀和模板题。

前缀和中数组下标为1~n。

前缀和:pre[i]=pre[i-1]+a[i];

某段区间 [l,r]的和:pre[r]-pre[l-1]

3. 代码实现

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
const int N=1e5+10;
int a[N],pre[N];

signed main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n,q; cin>>n>>q;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        pre[i]=pre[i-1]+a[i];
    }
    while(q--){
        int l,r; cin>>l>>r;
        cout<<pre[r]-pre[l-1]<<endl;
    }
    return 0;
}
相关推荐
1白天的黑夜114 天前
前缀和-1314.矩阵区域和-力扣(LeetCode)
c++·leetcode·前缀和
1白天的黑夜119 天前
前缀和-974.和可被k整除的子数组-力扣(LeetCode)
c++·leetcode·前缀和
闻缺陷则喜何志丹1 个月前
【前缀和 BFS 并集查找】P3127 [USACO15OPEN] Trapped in the Haybales G|省选-
数据结构·c++·前缀和·宽度优先·洛谷·并集查找
咚咚轩2 个月前
洛谷B3612 【深进1.例1】求区间和
前缀和
小学生的信奥之路3 个月前
力扣1991:找到数组的中间位置(前缀和)
数据结构·算法·leetcode·前缀和·数组
XYY3694 个月前
前缀和 一维差分和二维差分 差分&差分矩阵
数据结构·c++·算法·前缀和·差分
随便昵称4 个月前
蓝桥杯专项复习——前缀和和差分
c++·算法·前缀和·蓝桥杯
小卡皮巴拉4 个月前
【力扣刷题实战】矩阵区域和
开发语言·c++·算法·leetcode·前缀和·矩阵