Subsequence(尺取法)
2016-03-05 21:52
363 查看
Subsequence
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
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10890 | Accepted: 4503 |
2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5Sample 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;}
相关文章推荐
- UIImage 的imageWithContentsOfFile:path和imageNamed的区别
- UESTC 1251 谕神的密码【暴力枚举】
- (3) IOS笔记本——UIScrollView的其他应用
- POJ2299 Ultra-QuickSort 归并排序求逆序对
- 手势识别器(UIGestureRecognizer)- UIPanGestureRecognizer(拖拽)
- 手势识别器(UIGestureRecognizer)- UIPinchGestureRecognizer(捏合)
- [leetcode] 312. Burst Balloons
- 手势识别器(UIGestureRecognizer)- UIRotationGestureRecognizer(旋转)
- UESTC 758 P酱的冒险旅途【贪心】
- UESTC oj 758 P酱的冒险旅途
- 关于Float.MIN_VALUE 和 Float.MAX_VALUE
- 手势识别器(UIGestureRecognizer)- UISwipeGestureRecognizer(轻扫)
- 手势识别器(UIGestureRecognizer)- UILongPressGestureRecognizer(长按)
- 手势识别器(UIGestureRecognizer)- UITapGestureRecognizer(敲击)
- Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
- queue 之团队队列(摘)
- UESTC oj 谕神的密码
- IOS学习资源收集--开发UI控件相关
- UIImageView(loading...)
- LA 4255(p309)----Guess