#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<functional>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 100005;
const int inf = 1<<30;//0x7f;
int n,d;
int a[maxn],dp[maxn];//dp[i]为以Ai结尾满足小明序列要求的最长子序列的长度
struct node
{
int maxs;
}tree[maxn<<2];
void buildtree( int rt,int ld,int rd )
{
tree[rt].maxs = 0;
if( ld < rd ){
int mid = (ld+rd)>>1;
buildtree( rt<<1,ld,mid );
buildtree( rt<<1|1,mid+1,rd );
}
}
void updata( int rt,int ld,int rd,int pos,int val )
{
if( ld == rd ){
tree[rt].maxs = val;
return;
}
int mid = (ld+rd)>>1;
if( pos <= mid ) updata( rt<<1,ld,mid,pos,val );
else updata( rt<<1|1,mid+1,rd,pos,val );
tree[rt].maxs = max( tree[rt<<1].maxs , tree[rt<<1|1].maxs );
}
int query( int rt,int ld,int rd,int x,int y )
{
if( x <= ld && rd <= y )
return tree[rt].maxs;
int mid = (ld+rd)>>1;
if( y <= mid ) return query( rt<<1,ld,mid,x,y );
else if( x > mid ) return query( rt<<1|1,mid+1,rd,x,y );
else return max( query( rt<<1,ld,mid,x,y ),query( rt<<1|1,mid+1,rd,x,y ) );
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("data.txt","r",stdin);
#endif
while( scanf("%d%d",&n,&d) != EOF )
{
int Max = 0,ans = 1;
memset(dp,0,sizeof(dp));
for( int i = 1; i <= n; i ++ ){
scanf("%d",&a[i]);
Max = ( Max>a[i]?Max:a[i] );
}
buildtree( 1,0,Max );
for( int i = 1; i <= n; i ++ )
{
if( i - d - 1 > 0 ) updata( 1,0,Max,a[i-d-1],dp[i-d-1] );
if( a[i] > 0 ) dp[i] = query( 1,0,Max,0,a[i]-1 ) + 1; //dp[i]等于在i-d-1前最长子序列长度加一
else dp[i] = 1; //a[i]为0,dp[i]等于1
ans = max( ans,dp[i] );
}
printf("%d\n",ans);
}
return 0;
}
LIS解法
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn = 100005;
const int inf = 1<<30;
int n,k;
int a[maxn],dp[maxn],c[maxn];
//a数组存放序列
//dp记录在i点时最长的递增子序列长度
//c数组为每次查找时候的标记,记录路径
int bin( int t,int top )
{
int ld = 1,rd = top;
while( ld <= rd )
{
int mid = (ld+rd)/2;
if( t > c[mid] )
ld = mid+1;
else
rd = mid-1;
}
return ld;
}
int LIS()
{
int top = 0;
for( int i = 1; i <= n; i ++ )
{
dp[i] = bin(a[i],top);
if( dp[i] > top ) //更新最长长度
top = dp[i];
int j = i-k; //因为需要相隔为K
if( j > 0 && c[dp[j]] > a[j] )//查找标记
c[dp[j]] = a[j];
}
return top;
}
int main()
{
while(~scanf("%d%d",&n,&k) )
{
for( int i = 1; i <= n; i ++ )
{
scanf("%d",&a[i]);
c[i] = inf;
}
printf("%d\n",LIS());
}
return 0;
}