POJ3061 Subsequence[队列求区间和]

Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6746   Accepted: 2465

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

Source

 
 
 
 
题意:按照顺序给定一组数,求出这组树中和大于等于m的最短子序列。
 
 
题目的实质是维护一个队列,方向从左向右,保证队列中所有数值和大于等于m,并保证最短的长度值。
 
 
code:
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 int data[100100];
 7 int n,m;
 8 
 9 int fun()
10 {
11     int i=0,j;
12     int minx=0x7fffffff;
13     int sum=0;
14     for(j=0;j<n;)
15     {
16         while(sum<m&&j<n)
17             sum+=data[j++];
18         while(sum>=m)
19         {
20             minx=min(minx,j-i);
21             sum-=data[i++];            
22         }
23     }
24     if(minx==0x7fffffff)
25         return 0;
26     return minx;
27 }
28 
29 int main()
30 {
31     int t;
32     int i;
33     scanf("%d",&t);
34     while(t--)
35     {
36         scanf("%d%d",&n,&m);
37         for(i=0;i<n;i++)
38             scanf("%d",&data[i]);
39         printf("%d\n",fun());
40     }
41     return 0;
42 }
原文地址:https://www.cnblogs.com/XBWer/p/2692401.html