您的位置:首页 > 产品设计 > UI/UE

POJ-3061 Subsequence(队列求区间和)

2013-11-14 20:08 190 查看

Subsequence

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

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

Sample Output

2
3

题目大意:输入为一组n个正整数(10<n <100000),和一个正整数s(s<100000000)。编写一个程序找到序列的连续元素的子序列的最小长度,使其的总和大于或等于s。

#include<stdio.h>

#define maxn 100005
#define min(a,b) (a<b?a:b)

int n, s;
int a[maxn];

int min_length()
{
int sum = 0, i = 0, j;
int minx = 0x3f3f3f3f;
for (j = 0; j < n;)                //遍历每个元素
{
while (sum < s && j < n)
{
sum += a[j++];           //从头开始一个一个加,如果<s,则一直加
}
while (sum >= s)
{
minx = min(minx,j - i);         //j-i为这一段相加的长度
sum -= a[i++];                //在sum中减去最前面的一个元素值,在一开始减去a[0],之后a[1],a[2]……都要逐个减去。
//如n = 4, s = 5,序列为1 2 2 3,1+1+2=5后minx=3,j=3;minx=3,sum=5-1=4,i=1;
//sum=4+3=7,j=4;minx=3,sum=7-2=5,i=2;minx=2,sum=5-2=3,i=3;以计算最小长度)
}
}
if (minx == 0x3f3f3f3f)
return 0;
else
return minx;
}

int main()
{
int i, t;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &s);
{
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("%d\n", min_length());
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: