poj-3061-Subsequence


                                                                                                    Subsequence
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 11690Accepted: 4893

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

题意:给定你n个数,以及一个数S,要你在n个数的序列中找一个连续的子序列,使得
这个子序列的和大于等于S,且让序列长度尽可能的小,没有答案输出0.
题目链接:Subsequence

解题思路:因为子序列要要连续,那么用dp[i]存储前i个数的和,则从j到k序列的和为dp[k+1]-dp[i],
且长度就为 k-j+1。
这里利用了下  lower_bound()函数,又学会一个函数的使用方法,真是方便哈!

6.8补充:学习了尺取法,并用尺取法做了下,感觉想法和实现和巧妙!

代码:

//Subsequence

#include
   
   
    
    
#include
    
    
     
     
#include
     
     
      
      
#include
      
      
       
       
const int N = 1e5+10;
using namespace std;
int a[N],dp[N]={0};
int main()
{
    int T,n,s,i,ans;
    cin>>T;
    while(T--){
        scanf("%d%d",&n,&s);
        for(i=0;i
       
       
         <= dp[n] ;i++){ int t=lower_bound(dp+i,dp+n,dp[i]+s)-dp; //从第i个位置开始,找出第一个终点值,满足区间内和大于S。 ans = min(ans,t-i); //减去dp的首地址,即为区间长度 } printf("%d\n",ans); } } return 0; } /* 函数lower_bound()在first和last中的前闭后开区间进行二分查找, 返回大于或等于val的第一个元素位置。如果所有元素都小于val, 则返回last的位置 */ //尺取法 #include 
        
          #include 
         
           using namespace std; int a[100005]; int main() { int T,i,n,s,ans,sum,s1,t; cin>>T; while(T--){ cin>>n>>s; for(i=0;i 
          
            >a[i]; } ans=n+1,sum=t=0,s1=0; for(;;){ while(t < n && sum < s){//间接保证了推进起点后,不推进终点的情况 sum += a[t++]; //推进区间的中点 } if(sum < s) break; //出循环是因为包含了剩余所有的数,但区间和仍然小于S,接下来推进起点只会让和更小 ans=min(ans,t-s1); sum-=a[s1++]; //推进区间的起点 } if(ans > n) ans=0; //第一次就在在 sum < s 的判断跳出循环了 cout< 
           
             < 
             
            
           
          
         
       
      
      
     
     
    
    
   
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值