其他分享
首页 > 其他分享> > 滑动窗口专题

滑动窗口专题

作者:互联网

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;
}

标签:专题,窗口,cur,int,sum,d%,im,滑动,include
来源: https://www.cnblogs.com/preccrep/p/16410795.html