POJ3061 Subsequence(双指针)
来源:互联网 发布:乐视 知乎 编辑:程序博客网 时间:2024/05/16 05:26
题目链接:http://poj.org/problem?id=3061
Subsequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 8850 Accepted: 3510
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
210 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5
Sample Output
23
题意:给一个数组以及一个整数s,求出和大于等于S的长度最小的连续子序列。
这道题有两种方法,一种是前缀和加二分搜索。
子序列的和可以用前缀和快速求出,然后枚举起点后二分搜索即可。复杂度为O(nlogn)
第二种方法就是用两个指针进行扫描。首先移动尾指针jj,直到ii到jj之间的和大于sum,此时求出子序列的长度jj-ii;然后将头指针ii向后移动一位,再重复以上步骤,直到sum≥s不可能实现为止。
这个算法中,jj最多只需要变化n次,所以复杂度为O(n)。
#include <iostream>#include <cstdio>#include <cstring>#include <string>using namespace std;const int inf=0x3f3f3f3f;int n,s,a[100005];int main(){int T;scanf("%d",&T);while (T--){scanf("%d%d",&n,&s);for (int i=0;i<n;i++){scanf("%d",&a[i]);}int ii=0,jj=0,sum=0,ans=inf;//头指针ii和尾指针jjwhile (1){while (jj<n&&sum<s){sum+=a[jj];++jj;}if (sum<s) break;//找不到sum<s说明已经不会再有情况了,可以退出ans=min(ans,jj-ii);sum-=a[ii];++ii;}if (ans>n) ans=0;printf("%d\n",ans);}return 0;}
0 0
- POJ3061 Subsequence(双指针)
- POJ3061---Subsequence(尺取法)
- POJ3061---Subsequence(尺取法)
- Subsequence poj3061(尺取法)
- poj3061 Subsequence(尺取法)
- POJ3061 Subsequence
- POJ3061 Subsequence
- POJ3061 Subsequence
- poj3061---Subsequence
- POJ3061-Subsequence
- poj3061 Subsequence
- POJ3061-Subsequence
- POJ3061-Subsequence
- poj3061 Subsequence
- 【poj3061】Subsequence
- poj3061:Subsequence
- poj3061 Subsequence 尺取法
- poj3061 Subsequence ,尺取法
- enum
- oracle学习笔记 二
- 实验室第八周工作报告
- 第三章 内核对象
- sql的count的反过程
- POJ3061 Subsequence(双指针)
- Uncompressing Linux... done, booting the kernel (问题集锦)
- 工作周报八
- Android开发时提示Your project contains error(s),please fix them be
- 常见的几种索引简介
- STL中的list/set/map等容器clear之后的内存占用
- 编程题:写一个函数将其中的\t都转换成4个空格
- NuttX启动流程
- vi/vim模式下显示行号