eg:
HDU-1257
最长上升序列
a
1
<
a
2
<
a
3
<
⋯
<
a
n
a_1<a_2<a_3< \dots < a_n
a1<a2<a3<⋯<an
最长不下降序列
a
1
≤
a
2
≤
a
3
≤
⋯
≤
a
n
a_1 \leq a_2 \leq a_3 \leq \dots \leq a_n
a1≤a2≤a3≤⋯≤an
题意可以理解为求解最长上升序列
两种解法
第一种使用动态规划,第二种为贪心+二分:
详解博客https://blog.csdn.net/George__Yu/article/details/75896330
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
void hdu1257(){
int n;
while(cin>>n){
int *dis=new int [n];
for(int i=0;i<n;i++) cin>>dis[i];
int *d=new int [n];
//inital
int maxx=0;
d[0]=1;
for(int i=1;i<n;i++){
d[i]=1;
for(int j=0;j<i;j++){
if(dis[i]>dis[j]){
d[i]=max(d[i],d[j]+1);
}
}
maxx=max(maxx,d[i]);
}
cout<<maxx<<endl;
delete [] dis;
delete [] d;
}
}
void hdu1257x(){
int n;
while(cin>>n){
int *dis=new int [n];
int *d= new int [n];
for(int i=0;i<n;i++) {
cin>>dis[i];
d[i]=-1;
}
int ans=0;
d[0]=dis[0]; //put the first node to the d
for(int i=1;i<n;i++){
if(d[ans]>dis[i]){
//binary search to insert the node
int left=-1,right=ans;
while(right-left>1){
int mid=(left+right)/2;
if(d[mid]<dis[i]){
left=mid;
}else{
right=mid;
}
}
d[right]=dis[i]; //insert the node to array
}else if(d[ans]<dis[i]){ //add to the next
d[++ans]=dis[i];
}
}
cout<<ans+1<<endl;
}
}
int main(){
hdu1257x();
system("pause");
return 0;
}