[关闭]
@zhangche0526 2017-02-25T06:29:47.000000Z 字数 1173 阅读 972

尺取法

例题:POJ 3061


Subsequence

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 13348 Accepted: 5635

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

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

Sample Output

  1. 2
  2. 3

Source

Southeastern Europe 2006


  1. #include<iostream>
  2. #include<cstdio>
  3. #define min(a,b) (a<b?a:b)
  4. #define max(a,b) (a>b?a:b)
  5. using namespace std;
  6. const int MAXN=1e5;
  7. int N,S;
  8. int a[MAXN+1];
  9. int num;
  10. void solve()
  11. {
  12. int res=N+1;
  13. int s=0,t=0,sum=0;
  14. while(true)
  15. {
  16. while(t<N&&sum<S)
  17. sum+=a[t++];
  18. if(sum<S) break;
  19. res=min(res,t-s);
  20. sum-=a[s++];
  21. }
  22. if(res>N) res=0;
  23. cout<<res<<endl;
  24. }
  25. int main()
  26. {
  27. cin>>num;
  28. for(int tmp=1;tmp<=num;tmp++)
  29. {
  30. int i=1;
  31. cin>>N>>S;
  32. for(i=1;i<=N;i++) cin>>a[i];
  33. solve();
  34. }
  35. return 0;
  36. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注