Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 16520   Accepted: 7008

Description

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.

Input

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.

Output

For each the case the program has to print the result on separate line of the output file.if no answer, print 0.

Sample Input

2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5

Sample Output

2
3

Source

 
题目大意:t个测试数据 对于一个长度为N的序列 求出总和不小于S的连续子序列的长度的最小值。
题解:
解法一、
二分搜索
前缀和是满足单调性的,计算从每一个数开始总和刚好大于s的长度。具体实现就是
二分搜索s[i]+s是否存在于前缀和数组中,就是查找以i+1开头的总和刚好大于s的最短长度。
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int t,n,s,x;
int sum[];
int main(){
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&s);
for(int i=;i<=n;i++){
scanf("%d",&x);
sum[i]=sum[i-]+x;
}
if(sum[n]<s){
printf("0\n");
continue;
}
int res=n;
for(int i=;sum[i]+s<=sum[n];i++){
int t=lower_bound(sum+i+,sum+n+,sum[i]+s)-sum;
res=min(res,t-i);
}
printf("%d\n",res);
}
return ;
}
时间复杂度nlog(n)
解法二、
尺取法 时间复杂度O(n)
#include<iostream>
#include<cstdio>
using namespace std;
int res,t,n,s,l,r,sum;
int a[];
int main(){
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&s);
for(int i=;i<=n;i++)scanf("%d",&a[i]);
l=r=;sum=;res=n+;
for(;;){
while(r<=n&&sum<s){
sum+=a[r++];
}
if(sum<s)break;//必须先判断才能更新解
res=min(res,r-l);
sum-=a[l++];
}
if(res>n)printf("0\n");
else printf("%d\n",res);
}
return ;
}

最新文章

  1. Pyinstaller打包Selenium脚本为exe文件执行问题
  2. ThinkPad告别蓝快,自己使用VHD安 WIN8.1并成功激活
  3. php openssl 生成公私钥,根据网上文章整理的
  4. oracle srvctl 命令
  5. 应用在安卓和ios端APP的证件识别
  6. (译文)学习ES6非常棒的特性-字符串常量基础
  7. ArcGIS API for JavaScript 4.x 本地部署之Apache(含Apache官方下载方法)
  8. Hive基础测试操作
  9. JavaScript 对象部署 Iterator 接口
  10. python编写文件统计脚本
  11. python模块之时间模块
  12. 利用微信企业号的告警功能,联动检测ICMP的shell脚本
  13. 『TensorFlow』slim模块常用API
  14. 【转】利用python的KMeans和PCA包实现聚类算法
  15. Centos下SFTP双机高可用环境部署记录
  16. linux新增动态库后可执行程序找不到的问题
  17. node inspector
  18. Windows下卸载Apache、Mysql
  19. SDN期末作业博客
  20. 使用refind引导多系统

热门文章

  1. class文件无论是32位还是64位jdk编译出来的,都可以通用
  2. java中自带时间类使用方法实例 Date,Timestamp,DateFormat
  3. Tessellation (曲面细分) Displacement Mapping (贴图置换)
  4. ES7前端异步玩法:async/await理解 js原生API妙用(一)
  5. DDR 布线规则
  6. hdu5318 The Goddess Of The Moon (矩阵高速幂优化dp)
  7. Android添加系统级顶层窗口 和 WindowManager添加view的动画问题
  8. Linux的基本使用
  9. kubernetes调度之资源配额
  10. Swift高阶函数介绍(闭包、Map、Filter、Reduce)