7-122 最長連續遞增子序列 (20分)
輸入樣例:
15
1 9 2 5 7 3 4 6 8 0 11 15 17 17 10
輸出樣例:
3 4 6 8
具體代碼解釋見AC代碼:
#include<bits/stdc++.h>
using namespace std;
int a[100009];
queue<int> ans,q;
void clear(queue<int>& q){
queue<int> empty;
swap(empty,q);
}
int main(){
int n,cnt=0;
cin>>n;
for(int i=0; i<n; i++) cin>>a[i];
for(int i=0; i<n-1; i++){
if(a[i+1]<=a[i]){ //不連續遞增了
q.push(a[i]);
if(q.size()>ans.size()){
clear(ans); //清空隊列
while(!q.empty()){
ans.push(q.front());
q.pop();
}
}
clear(q);
}else{
q.push(a[i]);
}
}
if(a[n-1]>a[n-2]) q.push(a[n-1]); //上面的循環是到n-1的,所以這裏要判斷一下最後一個元素是否大於倒數第二個元素
//考慮到如果存在序列一直遞增的到最後一個元素,則需要判斷最後一個遞增序列和之前的最大序列進行比較,取最大的那個
if(q.size()>ans.size()){
while(!q.empty()){
if(cnt) cout<<" ";
cout<<q.front();
cnt++;
q.pop();
}
}else{
while(!ans.empty()){
if(cnt) cout<<" ";
cout<<ans.front();
cnt++;
ans.pop();
}
}
return 0;
}
歡迎大家批評改正!!!