https://blog.csdn.net/liuchuo/article/details/54428567
#include<iostream> #include<vector> #include<stdio.h> using namespace std; int n,m; vector<int>res,sum; void fun(int i,int &j,int &tmp){ int l= i,r =n; while(l<r){ int mid = (r+l)/2; if(sum[mid] - sum[i-1]>=m) r = mid; //二分查找不能l和r在更新时都 = mid 这里l =mid+1,将大于和小于合在一起,选择大于等于最小花费的位置, else l = mid+1; } j = r; tmp = sum[j] - sum[i-1]; } int main(){ cin>>n>>m; sum.resize(n+1); for(int i=1;i<=n;i++){ cin>>sum[i]; sum[i]+=sum[i-1]; } int minres = sum[n]; for(int i=1;i<=n;i++){ int j,tmp; fun(i,j,tmp); if(tmp>minres||tmp<m)continue; else if(tmp<= minres){ if(tmp<minres){ res.clear(); minres =tmp; } res.push_back(i); res.push_back(j); } } for(auto i = 0;i<res.size();i+=2){ printf("%d-%d\n",res[i],res[i+1]); } return 0; }