1. 程式人生 > >Subsequence(尺取法)

Subsequence(尺取法)

Subsequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10890 Accepted: 4503

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
題目大意:起初的想法是先找到這個序列裡最大的一個數m,然後在m前面的序列中找一個滿足條件的最短子序列,然後在m後面的序列中找一個滿足條件的子序列,比較這兩者的長度,取小的,但這種做法是不對的,因為m成了分界,m在中間的子序列沒被考慮在內,所以WA了好多次。。。汗!
正確的想法應該是,同時在m的前邊找找,後面找找
附上錯誤的程式碼:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAX 100100
int a[MAX],b[MAX];
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		int n,s,i,m=-1,sum=0,la=100003,lb=100003;
		scanf("%d%d",&n,&s);
		for(i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
			sum+=a[i];
			if(a[i]>a[m])
			{
				m=i;
			}
		}
	    if(sum<s)
	    {
	    	printf("0\n");
	    	continue;
	    }
	      
	    if(a[m]>=s)
	    {
	    	printf("1\n");
	    	continue;
	    }
	    int cnt=1; 
	    //向前找
	    for(i=0;i<n;i++)
	      b[i]=a[i]; 
		for(i=m;i>=0;i--)
		{
			cnt++;
			a[i-1]+=a[i];
			if(a[i-1]>=s)
			{
				la=cnt;
				break;
			}
		} 
		 //向後找
		   cnt=1;
		  for(i=0;i<n;i++)
	        a[i]=b[i]; 
		 for(int j=m;j<n;j++)
		 {
		 	  cnt++;
		 	a[j+1]+=a[j];
		 	if(a[j+1]>=s)
		 	{
		 		lb=cnt;
		 		break;
		 	}
		 }
		 if(la!=100003||lb!=100003) 
	 // if(la!=100003&&lb!=100003)第一次WA的地方 
	  {
	  	  if(la<=lb)
	  	    printf("%d\n",la);
	  	  else
	  	    printf("%d\n",lb);
	  }
	  else
	    printf("0\n"); 
	}
	return 0;
}