尺取法模板

编程入门 行业动态 更新时间:2024-10-25 00:31:59

尺取法<a href=https://www.elefans.com/category/jswz/34/1770549.html style=模板"/>

尺取法模板

天降馅饼
Description

棉帽子同学这天走在街上,突然看到前面很多钱袋,呈一字排开,每个袋面上都标有里面的钱数,棉帽子笑了,想着:不孬~

但是他也不想特别贪婪,他只想总共拿不少于S块钱,而且他要拿位置连续的钱袋(事儿事儿的),但是他还不知道该怎么拿…

聪明的你能不能帮他算出他最少要拿多少个钱袋.

Input
输入的第一行为整数n和S(1<=n<=100000,1<=S<=1e9);第二行为n个整数,a[i]代表第i个钱袋里的钱数,(0<=a[i]<=1e9).

Output
输出他最少要拿多少个钱袋.如果不存在这样的方案,输出-1.

Sample Input 1

5 7
5 4 3 2 1
Sample Output 1

2
Sample Input 2

3 5
1 1 1
Sample Output 2

-1

#include<iostream>
#include<math.h>
#include<algorithm>
using namespace std;int a[100009];int main(){int m,n;scanf("%d%d",&m,&n);long long ans=0;for(int i=1;i<=m;i++){scanf("%d",&a[i]);
//	cout<<a[i];ans+=a[i];	}if(ans<n){printf("-1\n");return 0;}int l=1,r=1;ans=0;int count=0;int cnt=999999;while(r<=m){while(ans<n&&r<=m){ans+=a[r];r++;count++;}while(ans>=n){ans-=a[l];l++;count--;}cnt=min(cnt,count+1);}cout<<cnt<<endl; 
}
Share

更多推荐

尺取法模板

本文发布于:2024-02-10 15:29:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1676055.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!