Description
Jessica's a very lovely girl wooed by lots of boys. Recently she has a problem. The final exam is coming, yet she has spent little time on it. If she wants to pass it, she has to master all ideas included in a very thick text book. The author of that text book, like other authors, is extremely fussy about the ideas, thus some ideas are covered more than once. Jessica think if she managed to read each idea at least once, she can pass the exam. She decides to read only one contiguous part of the book which contains all ideas covered by the entire book. And of course, the sub-book should be as thin as possible.
A very hard-working boy had manually indexed for her each page of Jessica's text-book with what idea each page is about and thus made a big progress for his courtship. Here you come in to save your skin: given the index, help Jessica decide which contiguous part she should read. For convenience, each idea has been coded with an ID, which is a non-negative integer.
Input
The first line of input is an integer P (1 ≤ P ≤ 1000000), which is the number of pages of Jessica's text-book. The second line contains P non-negative integers describing what idea each page is about. The first integer is what the first page is about, the second integer is what the second page is about, and so on. You may assume all integers that appear can fit well in the signed 32-bit integer type.
Output
Output one line: the number of pages of the shortest contiguous part of the book which contains all ideals covered in the book.
Sample Input
5
1 8 8 8 1
Sample Output
2
题目大意:给一个长度为n的序列,a1, a2, ....an,以及整数s,求出总和不小于s的连续子序列长度的最小值;
分析,如果枚举的话数量过多,也就是2^n,这个数据量不卡简直丧心病狂,
优化:首先ai到at之和大于等于s从a(i+1)开始到a(t1)只和大于s,那么t1 >= t ;
如果有sum < s 就不断的给sum 加上ai并将i自增
如果无法满足sum>s 那么就终止,否则的话就更新ans = min(ans,t - s )
代码:
/***********************************
@Auther Thunder01
poj 3062
尺取法
************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<algorithm>
#define MAX 100005
using namespace std;
int a[MAX];
int n,maxs,test;
int solve()
{
int t = 0, s = 0, sum = 0;
int ans = n + 1;
for ( ; ; )
{
while ( t < n && sum < maxs)
{
sum += a[t++];
}
if ( sum < maxs ) break;
ans = min(ans,t-s);
sum -= a[s++];
}
if ( ans > n ) ans = 0;
return ans;
}
int main()
{
//freopen("in.txt","r",stdin);
scanf("%d",&test);
while ( test-- )
{
scanf("%d %d",&n,&maxs);
for ( int i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
int ans = solve();
printf("%d\n",ans);
}
}