尺取法例题
Posted hao-tian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尺取法例题相关的知识,希望对你有一定的参考价值。
例1 , POJ3061: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的数组和一个整数m,求总和不小于m的连续子序列的最小长度
n = 10,m = 15
5 1 3 5 10 7 4 9 2 8
那么我们先用sum存当前这个子序列的和,从左边第一个数来存,直到这个子序列的和大于等于m为止,再记录下当前长度。
其实相当于当不满足条件就入队,然后得到队列长度,再将队首元素出队,再进行下一次的
入队,直到满足条件再次出队,并且将这一次的长度与历史最短长度进行取舍,最后扫到最
后的元素却无法再满足入队条件的时候就结束,此时用O(n)的时间就可以得到答案。
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
#include<iostream> #include<cstdio> #include <queue> using namespace std; int a[100005]; int main(){ int T; scanf("%d",&T); int n,m; while(T--) { scanf("%d%d",&n,&m); int ans = n+1; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } int now = 0; queue<int> q; int flag = 0; for(int i=0;i<n;i++) { q.push(a[i]); now+=a[i]; if(now>m) { while(now>=m) { flag = 1; int t = q.size(); ans = min(ans,t); now-=q.front(); q.pop(); } } } if(!flag) printf("0 "); else printf("%d ",ans); } }
未完。。
以上是关于尺取法例题的主要内容,如果未能解决你的问题,请参考以下文章