题解 | #【模板】前缀和#

【模板】前缀和

http://www.nowcoder.com/practice/acead2f4c28c401889915da98ecdc6bf

import java.util.; import java.util.; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int q = in.nextInt(); Long[] arr = new Long[n]; Long[] preSum = new Long[n + 1]; for(int i = 0;i < n;i ++){ arr[i] = in.nextLong(); } preSum[0] = 0L; for(int i = 0;i < n;i++){ preSum[i+1] = preSum[i ] + arr[i]; } while(q -- > 0){ int l = in.nextInt(); int r = in.nextInt(); System.out.println(preSum[r] - preSum[l - 1]); } } }

// public class Main { // public static void main(String[] args){ // Scanner sc = new Scanner(System.in); // int n = sc.nextInt(); // int q = sc.nextInt(); // //存放数组元素 // int[] arr=new int[n]; // //存放前缀和 // long[] presum=new long[n+1]; // for(int i=0;i<n;i++){ // arr[i]=sc.nextInt(); // presum[i+1]=presum[i]+arr[i]; // } // //q次查询 // while(q-->0){ // int l=sc.nextInt(); // int r=sc.nextInt(); // //输出查询结果 // System.out.println(presum[r]-presum[l-1]); // } // } // }

我居南半坡 文章被收录于专栏

多刷题,积蓄力量,欢迎讨论

全部评论

相关推荐

简历求拷打,海投简历发过去就已读不回了求大佬们指点
程序员牛肉:基本不能了,估计你得放弃秋招,九月份找实习之后明年的春招开始正式找工作
点赞 评论 收藏
分享
06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务