滑动窗口专题
Shopping in Mars (25)
Link
这道题还可以用前缀和+二分
做。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
int n,m;
int d[100010];
vector<pair<int,int>>ans;
int main() {
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)
scanf("%d",&d[i]);
int sum=0,i=1;
while(i<=n&&sum<m) sum+=d[i++];
int diff=sum-m,cur=1;
if(diff==0) printf("%d-%d\n",cur,i-1);
else ans.push_back({cur,i-1});
for(int j=i;j<=n;++j){
sum+=d[j];
while(sum>m){sum-=d[cur++];}
if(sum==m){
diff=0;
printf("%d-%d\n",cur,j);
}else{
sum+=d[--cur];
if(sum-m<diff){
ans.clear();
diff=sum-m;
ans.push_back({cur,j});
}else if(sum-m==diff)
ans.push_back({cur,j});
}
}
if(diff==0) return 0;
for(int i=0;i<ans.size();++i)
printf("%d-%d\n",ans[i].first,ans[i].second);
return 0;
}