POJ3061 Subsequence
这道题是POJ上id为3061的一道题,这道题总体来说比较简单,但是坑点也不少额,稍微不注意就WA了,好了,我们一起来看看题意吧:
我们先看下中文大致题意吧:
给定长度为n的正整数数列以及正整数S,求出总和不小于S的连续子串的长度的最小值,如果解不存在,则输出 0
下面的描述是来自POJ官网
题目描述
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.
示例1
输入
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
输出
2
3
题目链接: POJ3061 Subsequence
思路
:
这道题最最暴力的做法就是n2的时间复杂度,n2是会TLE(超时)的,应该进行优化,怎么优化呢,我们比较容易想到双指针算法!
我们来看看成功AC的代码吧:
#include<iostream> #include<cstring> #include<cmath> using namespace std; int t; int n,s; int a[100010]; int main(){ cin>>t; while(t--){ cin>>n>>s; memset(a,0,sizeof(a)); for(int i=1;i<=n;i++) cin>>a[i]; int r=0; int su=0; int len=n+1; for(int i=1;i<=n;i++){ while(r<=n&&su<s){ r++; su+=a[r]; } if(su>=s) len=min(len,r-i+1); su-=a[i]; } if(len>n) cout<<"0\n"; else cout<<len<<"\n"; } return 0; }