首页 > 其他 > 详细

POJ 3061 Subsequence 尺取法

时间:2018-04-05 01:04:27      阅读:235      评论:0      收藏:0      [点我收藏+]

题目:

Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18528   Accepted: 7921

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

题意:给定一个整数序列,求总和不小于S的最短连续子序列的长度。

思路:两种想法:(1)计算出第i位的前缀和。然后二分查找答案 O(nlogn) (2)尺取法,超过S后,前面开始减小,如果仍然满足条件 更新结果,否则继续向后增加。

代码:

技术分享图片
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<iostream>
 5 #include<string>
 6 #include<vector>
 7 #include<stack>
 8 #include<bitset>
 9 #include<cstdlib>
10 #include<cmath>
11 #include<set>
12 #include<list>
13 #include<deque>
14 #include<map>
15 #include<queue>
16 using namespace std;
17 typedef long long ll;
18 const double PI = acos(-1.0);
19 const double eps = 1e-6;
20 const int INF = 0x3f3f3f3f;
21 
22 const int MAXN = 1e5+10;
23 int a[MAXN];
24 int n = 0;
25 int S = 0;
26 
27 void solve(){
28     int res = n+1;
29     int s = 0;int t= 0;int sum =0;
30     for(;;){
31         while(t<n&&sum<S){
32             sum+=a[t++];
33         }
34         if(sum<S)    break;
35         res = min(res,t-s);
36         sum-=a[s++];
37     }
38     if(res>n){
39         printf("0\n");
40     }else{
41         printf("%d\n",res);
42     }
43 }
44 
45 int main(){
46     int T = 0;
47     scanf("%d",&T);
48     for(int t=0;t<T;t++){
49         scanf("%d %d",&n,&S);
50         for(int i=0;i<n;i++){
51             scanf("%d",&a[i]);
52         }
53         solve();
54     }
55     
56     return 0;
57 }
View Code

 

POJ 3061 Subsequence 尺取法

原文:https://www.cnblogs.com/caomingpei/p/8719704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!