牛客题解 | 【模板】前缀和

题目

题目链接

解题思路

  1. 问题分析:

    • 需要多次查询数组区间和
    • 直接累加会导致时间复杂度 \(\mathcal{O}(n*q)\)
    • 可以使用前缀和优化到 \(\mathcal{O}(n+q)\)
  2. 前缀和优化:

    • 预处理数组,计算前缀和
    • 对于查询 \([l,r]\),结果为 \(prefix[r] - prefix[l-1]\)
    • 预处理时间 \(\mathcal{O}(n)\),每次查询 \(\mathcal{O}(1)\)
  3. 实现要点:

    • 注意前缀和可能超出 \(\text{int}\) 范围,使用 \(\text{long long}\)
    • 注意输入的下标从 \(1\) 开始

代码

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, q;
    cin >> n >> q;
    
    // 读取数组
    vector<long long> prefix(n + 1, 0);  // 前缀和数组,0位置为0
    for(int i = 1; i <= n; i++) {
        int x;
        cin >> x;
        prefix[i] = prefix[i-1] + x;  // 计算前缀和
    }
    
    // 处理查询
    while(q--) {
        int l, r;
        cin >> l >> r;
        cout << prefix[r] - prefix[l-1] << endl;
    }
    
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int q = sc.nextInt();
        
        // 读取数组并计算前缀和
        long[] prefix = new long[n + 1];
        prefix[0] = 0;  // 0位置为0
        for(int i = 1; i <= n; i++) {
            prefix[i] = prefix[i-1] + sc.nextLong();
        }
        
        // 处理查询
        while(q-- > 0) {
            int l = sc.nextInt();
            int r = sc.nextInt();
            System.out.println(prefix[r] - prefix[l-1]);
        }
        
        sc.close();
    }
}
def main():
    n, q = map(int, input().split())
    
    # 读取数组并计算前缀和
    nums = list(map(int, input().split()))
    prefix = [0] * (n + 1)  # 前缀和数组,0位置为0
    for i in range(n):
        prefix[i + 1] = prefix[i] + nums[i]
    
    # 处理查询
    for _ in range(q):
        l, r = map(int, input().split())
        print(prefix[r] - prefix[l-1])

if __name__ == "__main__":
    main()

算法及复杂度

  • 算法:前缀和
  • 时间复杂度:预处理 \(\mathcal{O}(n)\),查询 \(\mathcal{O}(1)\),总体 \(\mathcal{O}(n+q)\)
  • 空间复杂度:\(\mathcal{O}(n)\),用于存储前缀和数组
posted @ 2025-02-21 17:35  wangxiaoxiao  阅读(24)  评论(0)    收藏  举报