原始的贪心模拟列车调度算法如下
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,i,j=0,flag,cnt=0,t,a[100010],b[100010];
cin>>n;
memset(b,0,sizeof(b));
cin>>a[0];
b[0]=a[0];
for(i=1;i<n;i++)
{
cin>>a[i];
flag=0;
if(a[i]>b[j])
{
j=j+1;
b[j]=a[i];
}
else{
for(t=j-1;t>=0;t--)
{
if(a[i]>b[t])
{
b[t+1]=a[i];
flag=1;
break;
}
}
if(flag==0)
{
b[0]=a[i];
}
}
}
for(i=0;i<n;i++)
{
if(b[i]!=0)
{
cnt++;
}
}
cout<<cnt<<endl;
return 0;
}
不会超时有非常简洁的代码如下:
#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
const int N = 1e5+200;
int n,a,dp[N];
int main(){
scanf("%d",&n);
fill(dp,dp+n,INT_MAX);
for(int i=0;i<n;++i){
scanf("%d",&a);
*lower_bound(dp,dp+n,a)=a;//贪心确定最长上升子序列存储在dp数组中
}
printf("%d\n",lower_bound(dp,dp+n,INT_MAX)-dp);
return 0;
}
由于集合自身有序,考虑set代替数组可能更加简单
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,i,j=0,flag,cnt=0,t,a[100010],b[100010];
cin>>n;
set<int> c;
for(i=0;i<n;i++)
{
cin>>t;
c.insert(t);
if(c.upper_bound(t)!=c.end())
{
c.erase(c.upper_bound(t));
}
}
cout<<c.size()<<endl;
return 0;
}