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 5Sample Output
2 3Source
Southeastern Europe 2006[Submit] [Go Back] [Status] [Discuss]
原来一直在用的方法是尺取法。。。。 尺取法 就像这个妹子一样~ 解释一下数据: 10 15 5 1 3 5 10 7 4 9 2 8
次数结果sum第一次5 1 3 5 10 7 4 9 2 824第二次5 1 3 5 10 7 4 9 2 819第三次5 1 3 5 10 7 4 9 2 818第四次5 1 3 5 10 7 4 9 2 815第五次5 1 3 5 10 7 4 9 2 817第六次5 1 3 5 10 7 4 9 2 820第七次5 1 3 5 10 7 4 9 2 815第八次5 1 3 5 10 7 4 9 2 819应该看到规律了吧 每次sum加到大于等于15的位置,然后从左边舍弃一个,判断当前sum的值,如果小于15就继续像妹子一样向前+一个数,取最短。否则就继续舍弃,总之每个sum的是满足条件的 如果sum不满足 就退出循环。
#include <stdio.h> #include <algorithm> using namespace std; int num[100000+10]; int main() { int t; scanf("%d",&t); while(t--) { int n,s; scanf("%d %d",&n,&s); for(int i=0;i<n;i++) scanf("%d",&num[i]); int sum=0,l=0,r=0,res=0x3fffffff; while(true) { while(sum<s&&r<n) { sum+=num[r]; r++; } if(sum<s) break; /* for(int i=l;i<r;i++) { printf("%d ",num[i]); } printf("\n");*/ res=min(res,r-l); sum-=num[l++]; } if(res!=0x3fffffff) printf("%d\n",res); else printf("0\n"); } return 0; }