Vjudge A - Subsequence

题目:

A - Subsequence
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.

Input:

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

Output:

2
3

题目大意:

给出了一个由N个正整数(10 < N < 100 000),每个都小于或等于10000的序列,以及一个正整数S(S < 100 000 000)。写一个程序,
找出序列中连续元素的子序列的最小长度,其总和大于等于S。
输入: 第一行是测试案例的数量。对于每个测试用例,程序必须从第一行读取数字N和S,用空格隔开。
序列的数字在测试案例的第二行给出,用空隔隔开。输入将随着程序的结束而结束。
输出: 对于每一个案例,程序必须在输出文件的不同行中打印结果,如果没有答案,则打印0。

实现代码:

#include <stdio.h>
#include <iostream>
#include<algorithm>
#include<string.h>

const int maxn = 100010;
int num[maxn],sum[maxn],n,s;

using namespace std;

int main()
{ 
	int t;
	cin >> t;
	while(t--)
	{
		cin >> n >> s;
		sum[0]=0;
		for(int i=1;i<=n;i++)
		{
			cin >> num[i];
			sum[i] = sum[i-1]+num[i];
			//sum[1]是数组num中前1个数的和,sum[2]是数组num中前2个数的和,后面类似;
		}
		if(sum[n]<s)
		{
			cout << 0 << endl;
			continue;
		}
		int ans = n;
		for(int j=1;sum[j]+s<=sum[n];j++)
		{
			int t = lower_bound(sum+j,sum+n,sum[j]+s)-(sum+j);
			//lower_bound(first,last,n)是找到区间内第一个不小于n的数的地址
			ans = min(ans,t);
			/*
			利用lower_bound从sum中第一个数开始找,如果第一个数加上s小于sum[n](数组内所有数的和),
			说明s小于数组的和减去第一个数,然后找到区间内第一个不小于sum[1]+s的数的位置,
			就是sum[1]+s大于数组前几个数的和,再减去前面第1个数的地址,
			就得到这数组一个子序列的和大于等于s,  得到t,数组内有很多种符合要求的子序列,
			我们要求数组内最短序列的长度,所以我要t的最小值(t的最大值为数组长度n),j自加,后面类似;
			*/
		}
		cout << ans << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值