您的位置:首页 > 产品设计 > UI/UE

Subsequence(尺取法)

2016-03-05 21:52 363 查看
Subsequence
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 10890Accepted: 4503
DescriptionA 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 sumof which is greater than or equal to S.InputThe 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. Theinput will finish with the end of file.OutputFor 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 100100int 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);elseprintf("%d\n",lb);}elseprintf("0\n");}return 0;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: