POJ 3061 尺取法



Language: Default
Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 17744   Accepted: 7557

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

Source

Southeastern Europe 2006
题意:取一段连续的数,然后让它们的和大于等于s,让这一段连续的长度最短。

思路:肯定要暴力枚举一下,枚举上起点和终点,然后去算,但是会超时,所以,换个思路

我们无非就是在这一段连续的数中寻找一段,他的和最好大于s,弄两个类似指针的东西,然后如果他俩之间的区间小于s,r往右移动,否则,l想右,肯定和暴力的结果一样。

My ugly code

#include 
#include 
#include 

using namespace std;
const int maxn=1e5+10;
int n,s;
int a[maxn];

int main(){

    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&s);
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);
        int mmax=0x3f3f3f3f;
        int l=1,r=1;
        int sum=a[1];
        while(l <= r && r <=n ){
            if(sum >= s){
                mmax=min(mmax,r-l+1);
                sum-=a[l];
                l++;
            }
            else{
                sum+=a[++r];
            }
        }
        if(mmax==0x3f3f3f3f) printf("0\n");
        else printf("%d\n",mmax);
    }

    return 0;
}





Language: Default
Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 17744   Accepted: 7557

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

Source

Southeastern Europe 2006

你可能感兴趣的:(poj,尺取法)