[PAT] Grade 1044 Shopping in Mars (25 minutes) (prefix and double pointer)

Meaning of the questions:

Enter a positive integer N and M (N <= 1e5, M <= 1e8), the next input N positive integers (<= 1e3), output in ascending order of "ij", i ~ j is equal to M or is minimal M is greater than the number of segments.

Code:

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

Guess you like

Origin www.cnblogs.com/ldudxy/p/11605695.html