首页 > 其他 > 详细

Subsequence

时间:2021-02-05 10:42:31      阅读:20      评论:0      收藏:0      [点我收藏+]
A sequence of N positive integers (10<N<100 000), each of them less than or equal 10000, and a positive integerS(S<100 000 000) are given. Write a program to nd the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.
Input
Many test cases will be given. For each test case the program has to read the numbers N and S ,
separated by an interval, from the rst line. The numbers of the sequence are given in the second line
of the test case, separated by intervals. The input will nish with the end of le.
Output
For each the case the program has to print the result on separate line of the output le.
Sample Input
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 < 100 000),每个都小于或等于10000,并且给出一个正整数S (S < 100 000 000)。编写一个程序,找出最小长度的序列中连续元素的子序列,其总和大于或等于S。
 
 

可以用暴力算法直接开解。(
 
用队列做优化也不错,加上二分法查找已经可以得到时间复杂度较低的算法了。
 
当然这道题可以做到更快。
用数组用前缀和记录下来,用上两个指针,一头一尾(队列)开始扫到n,若满足子序列其总和大于或等于S,就把队头指针向后移动。
 
完整代码如下:
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cctype>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 int Read(){//快读模板,数据较大
 9     char c;
10     int ans = 0;
11     c = getchar();
12     while(!isdigit(c))
13         c=getchar();
14     while(isdigit(c)){
15         ans = ans*10+c-48;
16         c = getchar();
17     }
18     return 0;
19 }
20 int main(){
21     while(cin>>n)//多组数据
22     {
23         memset(sum,0,sizeof(sum));//初始化数组
24         ans=def;
25         S=Read();
26         for(int i=1;i<=n;i++){//读入以及前缀和处理
27             a[i]=Read();
28             sum[i]=sum[i-1]+a[i];
29         }
30         int head=0,tail=1;
31         for(tail=1;tail<=n;tail++)
32         {
33             while(sum[tail]-sum[head]>=S)
34             {
35                 if(sum[tail]-sum[head]>=S)
36                     ans=min(ans,tail-head);
37                 head++;
38             }
39         }
40         printf("%d\n",(ans==def)?0:ans);
41     }
42     return 0;
43 }

 

Subsequence

原文:https://www.cnblogs.com/taotianzhufang/p/14376025.html

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