1A:Subsequence

题目来源
Question
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.

题意
给出了N个正整数(10 <N <100 000)的序列,每个正整数均小于或等于10000,并给出了一个正整数S(S <100 000 000)。 编写程序以查找序列中连续元素的子序列的最小长度,其总和大于或等于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

解法

若枚举所有的子段和, 时间复杂度为O(n^2), 直接爆炸,可以用尺取优化

代码

这个尺取我是用队列实现的(其实是我一开始看不懂循环的题解)

#include <iostream>
#include <queue>
using namespace std;

const int INF =  1000000000;
int a[1000005];
int main(){
 queue <int>que;
 int T;
 cin >> T;
 while(T--){
  int n, S;
  cin >> n >> S;
  for(int i=0; i<n; ++i) cin >> a[i];
  que.push(a[0]); 
  int k = 1;
  int ans = INF;
  int sum = a[0];
  while(que.size()){
   if(sum >= S){//若不小于 S, 更新ans, sum减去先加入的元素,然后把它弹出
    ans = min(ans,int (que.size()));
    sum -= que.front();
    que.pop();
   }
   else{
    if(k==n) break;//若队列的 sum并且所有元素都加进来了,则sum不可能再增加,break 
    que.push(a[k]);//压入下一个元素 
    sum += a[k++];
   }
  }
  while(que.size()){//把队列的所有元素弹出
   que.pop();   //避免对下个测试样例的影响 
  }
  //ans没更新的话 说明无法达到 S, 输出0 
  if(ans != INF) cout << ans << endl;
  else cout << 0 << endl;
  
 }
 
 return 0;
}
发布了14 篇原创文章 · 获赞 0 · 访问量 156

猜你喜欢

转载自blog.csdn.net/loaf_/article/details/103952593
1A