加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

【PAT甲级】1044 Shopping in Mars (25 分)(前缀和,双指针)

发布时间:2020-12-16 09:12:03 所属栏目:百科 来源:网络整理
导读:题意: 输入一个正整数N和M(N=1e5,M=1e8),接下来输入N个正整数(=1e3),按照升序输出"i-j",i~j的和等于M或者是最小的大于M的数段。 代码: #define HAVE_STRUCT_TIMESPEC #includebits/stdc++.h using namespace std; int a[100007]; int sum[100007];

题意:

输入一个正整数N和M(N<=1e5,M<=1e8),接下来输入N个正整数(<=1e3),按照升序输出"i-j",i~j的和等于M或者是最小的大于M的数段。

代码:

#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
int a[100007];
int sum[100007];
vector<pair<int,int> >ans;
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n,m;
cin>>n>>m;
for(int i=1;i<=n;++i){
cin>>a[i];
sum[i]=sum[i-1]+a[i];
}
int l=0,t=0,mn=1e9;
for(int i=0;i<=n;++i){
t-=a[i];
while(t<m&&l<=n)
t+=a[l++];
if(t>=m&&t<mn){
mn=t;
ans.clear();
ans.push_back({i+1,l-1});
}
else if(t==mn)
ans.push_back({i+1,l-1});
}
cout<<ans[0].first<<"-"<<ans[0].second;
for(int i=1;i<ans.size();++i)
cout<<"n"<<ans[i].first<<"-"<<ans[i].second;
return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读