如何解决如何找到满足要求的子序列?
我正在寻找一种方法来从求和满足问题所需最小和的序列中搜索最小后续大小。
示例(请注意索引从0开始):
arr[]={5,1,3,5,10,7,4,9,2,8}
sum = 15
所以答案应该是2,因为子序列的最小大小来自
a[3]-a[4].
arr[]={1,5}
sum = 11
所以答案应该是3,因为子序列的最小大小是
a[2]-a[4].
#include <bits/stdc++.h>
using namespace std;
int main(){
vector <int> sequence;
int sequenceSize,sumAsked;
cin>>sequenceSize>>sumAsked;
int sum=0,count=sequenceSize,front=0,back=sequenceSize-1;
for(int i=0; i<sequenceSize; i++){
int j;
cin>>j;
sequence.push_back(j);
sum+=j;
}
if(sum<sumAsked){
cout<<0<<endl;
}
else{
while(sum>sumAsked){
if(sequence[front]>=sequence[back]){
sum-=sequence[back];
back--;
count--;
}
else{
sum-=sequence[front];
front++;
count--;
}
}
cout<<count+1<<endl;
}
}
该代码似乎可以在两个测试用例上正常工作,但是在线判断上却出错了。有什么更好的代码或方法可供我使用吗?
解决方法
我实际上得到了法官的accepted
答复,看起来像这样,
#include <bits/stdc++.h>
#define f first
#define s second
typedef long long int lli;
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int sequenceSize,sumAsked,sum=0;
cin>>sequenceSize>>sumAsked;
vector <int> sequence;
for(int i=0; i<sequenceSize; i++){
int j;
cin>>j;
sequence.push_back(j);
sum+=j;
}
if(sum<sumAsked) cout<<0<<endl; //whether to check it's possible or not to get the answer,else{ //otherwise it prints 0
vector <int> note;
int currentPos=0,currentSum=0,count=0;
int temp=sequence[currentPos];
for(int i=0; i<sequenceSize; i++){
currentSum+=sequence[i]; //here we add the sum one by one from the sequence
count++;
while(!(currentSum-temp<sumAsked)){ //here we reduce the size of the 'window'
currentSum-=temp; //until it's just enough to hold the sum
count--;
cur++;
temp=sequence[cur];
note.push_back(count); //to take note all possible 'window' size
}
}
for(int i=0; i<note.size(); i++){
count=min(count,note[i]); //to search the best possible minimum answer
}
cout<<count<<endl;
}
return 0;
}
尽管如此,我认为有可能不记下向量上的所有答案,但我认为它已经足够好了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。