UVALive - 2678:Subsequence

Subsequence

来源:UVALive

标签:

参考资料:

相似题目:

题目

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.

输入

Many test cases will be given. 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.

输入样例

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

输出样例

2
3

参考代码

#include
#define MAXN 100005
int arr[MAXN];
int main(){
	int n,S;
	while(~scanf("%d%d",&n,&S)){
		for(int i=0;i<n;i++){
			scanf("%d",&arr[i]);
		}
		int sum=0;//当前区间和
		int cnt=0;//当前区间的数字个数
		int ans=n;//所求答案
		int flag=0;//是否存在答案
		int i=0,j=0;
		while(i<n){
			sum+=arr[i];
			cnt++;
			if(sum>=S){
				flag=1;
				while(j<i){
					if(sum-arr[j]<S) break;
					sum-=arr[j];
					cnt--;
					j++;
				}
				ans=ans<cnt?ans:cnt;
			}
			i++;
		}
		if(flag) printf("%d\n",ans);
		else printf("0\n");
	}
	return 0;
}

你可能感兴趣的:(【记录】算法题解)