求字段和问题

damotiansheng 2011-11-13 08:50:57
Petr is a Bachelor of Mathematics. He is about to graduate, and need to finish a graduation design. His design is about sum of an array. He is given an array of positive numbers, and a number M. He is asked to find out how many sub-array have a sum that is less than M.

Input

There are several cases in the input. For each case, first given a number n, which tells how many numbers are there in the array, and a M, followed by n numbers.
n will be positive and no larger than 20000,while M less than 400000000,your given numbers in the array will be no larger than 20000. n=0 and M=0 terminates the input.

Output

Output the answer for each case, one in a line.

Sample Input

5 7
1 1 4 5 2
2 100
10 9
0 0

Sample Output

8
3


请问有什么比较好的算法不,要求其复杂度低于O(n^2),不然超时了,不使用2层遍历
...全文
53 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
凡心未灭 2011-11-13
  • 打赏
  • 举报
回复
可以先对输入数据进行排序,
比如,如果input[0] + input[2]>=M,后面input[0] + input[3]的就不需要比较了.虽然还是二层遍历,不过比较次数会少一点,在加上排序所用时间……难说,LZ试一下

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧