HDU-2836 Traversal 树状数组+DP+离散化

题目链接:HDU-2836

主要思路:

若是用普通的dp,dp开一维,dp[i]表示以i结尾的子序列的方案数.故dp[i]=sum(dp[j])(i-h<=j<=i+h).复杂度为O(N*H).

在这时可以用树状数组维护dp数组的前缀和,dp[i]=sum(i+h)-sum(i-h-1).

而由于数值太大,故用离散化.

#include<cstdio>
#include<cstring>
#include<algorithm>
#define lowbit(x) x&-x
#define P 9901
#define M 100005
using namespace std;
int n,C[M],a[M],b[M],h,c[M];
void Add(int x,int d){
	while(x<=n){
		C[x]=(C[x]+d)%P;
		x+=lowbit(x);
	}
}
int sum(int x){
	int res=0;
	while(x){
		res=(res+C[x])%P;
		x-=lowbit(x);
	}
	return res;
}
int main(){
	while(~scanf("%d%d",&n,&h)){
		int ans=0;
		memset(C,0,sizeof(C));
		for(int i=1;i<=n;i++)scanf("%d",&a[i]),b[i]=a[i];
		sort(b+1,b+n+1);
		int C=unique(b+1,b+n+1)-b-1;//去重 C为去重后元素个数 
		for(int i=1;i<=n;i++)c[i]=lower_bound(b+1,b+C+1,a[i])-b;//由于数值太大故用离散化 
		for(int i=1;i<=n;i++){
			int L=lower_bound(b+1,b+C+1,a[i]-h)-b;//最小的比a[i]-h大的元素的离散化后的值 
			int R=upper_bound(b+1,b+C+1,a[i]+h)-b-1;//最大的比a[i]+h小的元素的离散化后的值 
			int add=sum(R)-sum(L-1);
			add=(add%P+P)%P;//注意,取模后的sum(R)不一定比sum(L-1)小 
			ans=(ans+add)%P;
			Add(c[i],add+1);
		}
		printf("%d\n",ans);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_35320178/article/details/81113536
今日推荐