Subsequence

TimeLimit:1000MS  MemoryLimit:65536K
64-bit integer IO format:%lld
 
问题描述:
A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.
 
输入要求:
The first line is the number of test cases. For each test case the program has to read the numbers N and S, separated by an interval, from the first line. The numbers of the sequence are given in the second line of the test case, separated by intervals. The input will finish with the end of file.
 
输出要求
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
 
SampleInput
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
SampleOutput
2
3
思路:这题求的是满足要求的子序列里最短的序列长度,我们会想一段一段的进行筛选,也就是尺取法;我们可以先定两个标记i、j指向含N个元素的数组的首位,用sum来存储子序列,如果sum小于目标数M,则i++,否则sum减去j指向的元素且j++,随即计数器ans存储短的那个子序列的长度。
详见代码:

j=sum=i=0;
ans=N+1;

while (1)
{
while(i<N&&sum<M)
sum+=a[i++];
if(sum<M)//如果在之前一个while里加完还是小于M则不可能再比M大了
break;
ans=ans<i-j?ans:i-j;
sum-=a[j];
j++;
}

最新文章

  1. Javascript下拉导航
  2. c#.net循环将DataGridView中的数据赋值到Excel中,并设置样式
  3. iOS开发者帐号流程
  4. 【mysql5.6】下载安装
  5. 离线应用Application Cache详解
  6. cocos2d-x混合BlendFunc的使用
  7. 添加“返回顶部”小图标按钮的JS(JavaScript)代码详解
  8. 搭建自己的Git服务器
  9. OC语言中如何在便利构造器中利用便利初始化进行初始化
  10. 对Java的初识
  11. mysql一些函数的记录
  12. mybatis一对多查询之collection的用法
  13. C#读取word内容实践
  14. Android Selinux
  15. PAT 乙级 1017 A除以B (20) C++版
  16. 在centos xmanager工具环境下启动 xwindow
  17. 数位dp小结
  18. CocoaPods iOS 开源库管理
  19. 九度 1552 座位问题(递推DP)
  20. Android的Fragment中onActivityResult不被调用

热门文章

  1. mysql中联合查询
  2. docker+mesos+marathon
  3. 转--- 秒杀多线程第七篇 经典线程同步 互斥量Mutex
  4. 题解 P2089 【烤鸡】
  5. 51nod 1277字符串中的最大值(拓展kmp)
  6. WPF 如何加载图片
  7. windows主机防护
  8. 【51Nod1386】双马尾机器人Description 解题报告
  9. error 65: access violation at 0x40021000 : no &#39;read&#39; permission
  10. Machine Learning in Action-chapter2-k近邻算法