当前位置: 首页 > news >正文

Subarray Sums II

题目描述

Given an array of n integers, your task is to count the number of subarrays having sum x.

输入

The first input line has two integers n and x: the size of the array and the target sum x.
The next line has n integers a1,a2,...,an: the contents of the array.
Constraints
1 ≤ n ≤ 2\times10^5
-10^9 ≤ x,ai ≤ 10^9

输出

Print one integer: the required number of subarrays.

样例输入
5 7
2 -1 3 5 -2
样例输出
2
思路分析

利用前缀和 k=prefix[i]-prefix[j](j<i),加哈希表

初始哈希表mp[0]=1。

在输入数组x的过程中:先计算出前缀和prefix[i](prefix[i]=x[1]+...+x[i]);然后查找j(j<i)满足k=prefix[i]-prefix[j],也就是prefix[j]=prefix[i]-k,更新和为k的子数组数量ans为ans+mp[prefix[j]];最后将prefix[i]存入哈希表。

代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,k,x;
ll ans,prefix;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>n>>k;map<ll,int>mp;mp[0]=1;for(int i=1;i<=n;i++){cin>>x;prefix+=x;ans+=mp[prefix-k];mp[prefix]++;}cout<<ans;return 0;
}
http://www.dtcms.com/a/331083.html

相关文章:

  • EtherCAT概念介绍
  • Python入门第1课:环境搭建与第一个程序“Hello World”
  • python学习DAY41打卡
  • 前端已死,AI技术正在重塑前端软件工程师
  • 护照查验接口牢筑跨境场景安全防线-JavaScript集成示例
  • Elasticsearch ABAC 配置:实现动态、细粒度的访问控制
  • 玩转Docker | 使用Docker部署JSON格式化工具ZJSON
  • Java-数构map和set
  • 高效解决 pip install 报错 SSLError: EOF occurred in violation of protocol
  • P5967 [POI 2016] Korale 题解
  • Transformer之多头注意力机制和位置编码(二)
  • Canon PowerShot D30相机 CHDK 固件 V1.4.1
  • 5.Ansible-playbook-模块介绍(知识点补充)
  • 【Postgresql】实现 PostgreSQL 全量审计日志:记录所有 SQL 操作及来源
  • 【C++】细说继承(2w字详解)
  • ROS机器人云实践案例博客建议和范文-AI版本
  • imx6ull-驱动开发篇24——Linux 中断API函数
  • MATLAB绘制各种心形曲线
  • window显示驱动开发—在混合系统中使用跨适配器资源
  • nginx-集成prometheus监控(k8s)
  • GitHub 热榜项目 - 日榜(2025-08-14)
  • 一、linux内存管理学习(1):物理内存探测
  • 京东商品列表API开发指南
  • OpenCV对椒盐处理后的视频进行均值滤波处理
  • Opencv 边界填充 图像运算 阈值处理 和图像平滑处理
  • 文件上传接口接收不到文件入参
  • 题解:P4777 【模板】扩展中国剩余定理(EXCRT)
  • Qt项目查找依赖库打包
  • IDEA、Pycharm、DataGrip等激活破解冲突问题解决方案之一
  • Springboot项目重启后Session依旧存在