ZOJ-3349 Special Subsequence 线段树优化DP

时间:2023-03-09 05:30:38
ZOJ-3349 Special Subsequence 线段树优化DP

  题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3349

  题意:给定一个数列,序列A是一个满足|Ai-Ai-1| <= d的一个序列,其中Ai为给定数列中的元素,要保持相对顺序,求最长的序列A。

  显然用DP来解决,f[i]表示以第i个数结尾时的最长长度,则f[i]=Max{ f[j]+1 | j<i && |num[j]-num[i]|<=d }。直接转移复杂度O(n^2),超时。显然对于每个数num只要保存最大的f值就可以了,然后就是查找num[j]在区间[num[i]-d, num[i]+d]的最大的f[j],用颗线段树维护就可以了。。

 //STATUS:C++_AC_480MS_3008KB
#include <functional>
#include <algorithm>
#include <iostream>
//#include <ext/rope>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
//using namespace __gnu_cxx;
//define
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1.0)
//typedef
typedef long long LL;
typedef unsigned long long ULL;
//const
const int N=;
const int INF=0x3f3f3f3f;
const int MOD=1e+,STA=;
const LL LNF=1LL<<;
const double EPS=1e-;
const double OO=1e15;
const int dx[]={-,,,};
const int dy[]={,,,-};
const int day[]={,,,,,,,,,,,,};
//Daily Use ...
inline int sign(double x){return (x>EPS)-(x<-EPS);}
template<class T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
template<class T> inline T lcm(T a,T b,T d){return a/d*b;}
template<class T> inline T Min(T a,T b){return a<b?a:b;}
template<class T> inline T Max(T a,T b){return a>b?a:b;}
template<class T> inline T Min(T a,T b,T c){return min(min(a, b),c);}
template<class T> inline T Max(T a,T b,T c){return max(max(a, b),c);}
template<class T> inline T Min(T a,T b,T c,T d){return min(min(a, b),min(c,d));}
template<class T> inline T Max(T a,T b,T c,T d){return max(max(a, b),max(c,d));}
//End int num[N],order[N],hig[N<<],f[N];
int n,d; void update(int l,int r,int rt,int w,int val)
{
if(l==r){
hig[rt]=max(hig[rt],val);
return ;
}
int mid=(l+r)>>;
if(w<=mid)update(lson,w,val);
else update(rson,w,val);
hig[rt]=max(hig[rt<<],hig[rt<<|]);
} int query(int l,int r,int rt,int L,int R)
{
if(L<=l && r<=R){
return hig[rt];
}
int mid=(l+r)>>,ret=;
if(L<=mid)ret=max(ret,query(lson,L,R));
if(R>mid)ret=max(ret,query(rson,L,R));
return ret;
} int main()
{
// freopen("in.txt","r",stdin);
int i,j,m,L,R,lnum,rnum,ans,w;
while(~scanf("%d%d",&n,&d))
{
for(i=;i<n;i++){
scanf("%d",&num[i]);
order[i]=num[i];
}
sort(order,order+n);
m=unique(order,order+n)-order; mem(hig,);ans=;
for(i=;i<n;i++){
lnum=num[i]-d;rnum=num[i]+d;
L=lower_bound(order,order+m,lnum)-order;
R=upper_bound(order,order+m,rnum)-order-;
f[i]=query(,m-,,L,R)+;
w=lower_bound(order,order+m,num[i])-order;
update(,m-,,w,f[i]);
ans=max(ans,f[i]);
} printf("%d\n",ans);
}
return ;
}