Subsequence
2016-02-05 15:45
465 查看
题意:
求N个整数中相加的S的最少个数
思路:
a[i]表示前i个数的和,然后枚举终点,当遇到a[j-1]<=a[i]-s,即a[i]-a[j-1]>=s时累加j直到i-j最短,记录最小值
代码:
求N个整数中相加的S的最少个数
思路:
a[i]表示前i个数的和,然后枚举终点,当遇到a[j-1]<=a[i]-s,即a[i]-a[j-1]>=s时累加j直到i-j最短,记录最小值
代码:
#include<cstdio> #include<algorithm> #include<iostream> using namespace std; int s, n; int a[100005]; int main() { int t; while(scanf("%d%d", &n, &s) != EOF) { for(int i=1; i<=n; i++) { scanf("%d", &t); a[i] = a[i-1] + t; } int ans = n+1; int j=1; for(int i=1; i<=n; i++) { if(a[j-1] > a[i]-s) continue;//j-1意思是包含j while(a[j-1] <= a[i]-s) j++;//多加了一个 ans = min(ans, i-j+1);//所以这里要补上 } printf("%d\n", ans==n+1?0:ans+1);//长度是相减加一 } return 0; }
相关文章推荐
- Handler、looper、message、messageQueue
- 处理错误TypeError: initial_value must be unicode or None, not str
- ZwQueryValueKey routine
- 【IOS】分隔视图控制器 (UISplitViewController)
- 封装实现UIButton左文字右图片
- 用Method Swizzling来避免数组越界与可变字典value值为nil造成的程序崩溃
- 基于脚本的动画的计时控制(“requestAnimationFrame”)(转)
- Error:Gradle version 2.2 is required. Current version is 1.12
- ExAcquireResourceExclusiveLite routine
- 自己定义UITabBarController
- Oc-语句总结(5)-NSnumber/NSvalue/NSDate
- 时间选择器 UIDatePicker 简单的创建方法
- ExAcquireResourceSharedLite routine
- Zoho Recruit -求职者审批表
- Solr DocValues详解
- iOS7系统中的坑——UITableViewCellScrollView
- 使用Hibernate时出现“could not execute query”异常
- iOS开发——UILabel自适应较多的文本
- iOS9 升级后UIAlertController的简单使用
- iOS之UIView加边框及边框颜色