题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3450
题目大意:寻找某个整数列中的完美子序列(相邻之间差不超过d)个数.
题目思路:dp[x]=dp[i]+...+dp[j](a[]为整数列,a[i],a[j]的值和a[x]的差的觉得值不超过d),dp[]中存的为一当前位置结尾完美子序列的个数.),求dp[i]+...+dp[j]同样用线段树或树状数组,查找i,j的值可以把x-d和x+d一起存到进行离散化这样就不用写上下界函数了,当然数组要开3倍.
代码:
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <math.h> #include <time.h> #include <stack> #include <queue> #include <map> #include <set> #include <vector> #include <string> #include <iostream> #include <algorithm> using namespace std; #define ull unsigned __int64 #define ll __int64 //#define ull unsigned long long //#define ll long long #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 #define middle (l+r)>>1 #define MOD 9901 #define esp (1e-10) const int INF=0x3F3F3F3F; //const double pi=acos(-1.0); const int N=300010; int n,m; ll a[N],sum[N],hash[N]; void mod(ll& x){x= x<MOD? x:x%MOD;} int lowbit(int x){return x&(-x);} void Add(int pos,ll c){ while(pos<=m) mod(sum[pos]+=c),pos+=lowbit(pos); } ll Sum(int pos){ ll r=0; while(pos>0) mod(r+=sum[pos]),pos-=lowbit(pos); return r; } int bs(ll key,int size,ll A[]){ int l=0,r=size-1,mid; while(l<=r){ mid=middle; if(key>A[mid]) l=mid+1; else if(key<A[mid]) r=mid-1; else return mid; } return -1; } int main(){ //freopen("1.in","r",stdin); //freopen("1.out","w",stdout); int i,j,k,pos; ll ret,d,tmp; char op[2]; //int T,cas;scanf("%d",&T);for(cas=1;cas<=T;cas++) while(~scanf("%d%I64d",&n,&d)){ for(i=j=0;i<n;i++){ scanf("%I64d",&a[i]); hash[j++]=a[i]; hash[j++]=a[i]-d; hash[j++]=a[i]+d; } sort(hash,hash+j); for(i=m=1;i<j;i++) if(hash[i]!=hash[i-1]) hash[m++]=hash[i]; memset(sum,0,sizeof(sum)); for(i=0,ret=0;i<n;i++){ tmp=Sum(bs(a[i]+d,m,hash)+1)+MOD-Sum(bs(a[i]-d,m,hash)); mod(ret+=tmp); Add(bs(a[i],m,hash)+1,tmp+1); } printf("%I64d\n",ret); } return 0; }