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<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<queue> #include<stack> #include<set> #include<map> #include<vector> #include<cmath> const int maxn=1e5+5; typedef long long ll; using namespace std; ll a[maxn]; ll sum[maxn]; int main() { int n,m; cin>>n>>m; for(int t=1;t<=n;t++) { scanf("%lld",&a[t]); } for(int t=1;t<=n;t++) { sum[t]=sum[t-1]+a[t]; } int l,r,mid; if(sum[n]<m) { cout<<"-1"<<endl; return 0; } else { int minn=0x3f3f3f3f; for(int t=1;t<=n;t++) { int pos= lower_bound(sum,sum+n+1,sum[t-1]+m)-sum; if(pos<=n) minn=min(minn,pos-t+1); } cout<<minn<<endl; } }