• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
youdiankun
博客园    首页    新随笔    联系   管理    订阅  订阅

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

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。

 1 #include<stdio.h>
 2 
 3 #define maxn 100005
 4 #define min(a,b) (a<b?a:b)
 5 
 6 int n, s;
 7 int a[maxn];
 8 
 9 int min_length()
10 {
11     int sum = 0, i = 0, j;
12     int minx = 0x3f3f3f3f;
13     for (j = 0; j < n;)                //遍历每个元素
14     {
15         while (sum < s && j < n)
16         {
17             sum += a[j++];           //从头开始一个一个加,如果<s,则一直加
18         }
19         while (sum >= s)
20         {
21             minx = min(minx,j - i);         //j-i为这一段相加的长度
22             sum -= a[i++];                //在sum中减去最前面的一个元素值,在一开始减去a[0],之后a[1],a[2]……都要逐个减去。
23                                            //如n = 4, s = 5,序列为1 2 2 3,1+1+2=5后minx=3,j=3;minx=3,sum=5-1=4,i=1;
24                                            //sum=4+3=7,j=4;minx=3,sum=7-2=5,i=2;minx=2,sum=5-2=3,i=3;以计算最小长度)
25         }
26     }
27     if (minx == 0x3f3f3f3f)
28         return 0;
29     else 
30         return minx;
31 }
32 
33 int main()
34 {
35     int i, t;
36     scanf("%d", &t);
37     while (t--)
38     {
39         scanf("%d%d", &n, &s);
40         {
41             for (i = 0; i < n; i++)
42                 scanf("%d", &a[i]);
43             printf("%d\n", min_length());
44         }
45     }
46     return 0;
47 }

 

posted @ 2013-11-14 20:08  youdiankun  阅读(212)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3