Problem Description
For a set of sequences of integers{a1,a2,a3,...an}, we define a sequence{ai1,ai2,ai3...aik}in which 1<=i1<i2<i3<...<ik<=n, as the sub-sequence of {a1,a2,a3,...an}. It is quite obvious that a sequence with the length n has 2^n sub-sequences. And for a sub-sequence{ai1,ai2,ai3...aik},if it matches the following qualities: k >= 2, and the neighboring 2 elements have the difference not larger than d, it will be defined as a Perfect Sub-sequence. Now given an integer sequence, calculate the number of its perfect sub-sequence.
Input
Multiple test cases The first line will contain 2 integers n, d(2<=n<=100000,1<=d=<=10000000) The second line n integers, representing the suquence
Output
The number of Perfect Sub-sequences mod 9901
Sample Input
4 2 1 3 7 5
大佬的分析,写的很棒,有些地方没有完全理解;
<span style="font-size:18px;">#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN =100000+100;
const int MOD=9901;
struct node
{
int v;
int index;
bool operator <(const node&b)const
{
return v<b.v;
}
}nodes[MAXN];
int n,D;
int a[MAXN],L[MAXN],R[MAXN];
int c[3][MAXN];
int b[MAXN];
int lowbit(int x)
{
return x&(-x);
}
int sum(int i,int x)
{
int res=0;
while(x)
{
res +=c[i][x];
res%=MOD;//不加这句就是WA
x-=lowbit(x);
}
return res;
}
void add(int i,int x,int v)
{
while(x<MAXN)
{
c[i][x]+=v;
c[i][x]%=MOD;
x+=lowbit(x);
}
}
int find_L(int i)//找到初值为b[i]的数能接触到的新值的下界
{
int l=1,r=n,max_v=b[i];
while(r>l)
{
int mid= l+(r-l)/2;
if(max_v-nodes[mid].v<D)
r=mid;
else if(max_v-nodes[mid].v == D)
r=mid;
else
l=mid+1;
}
return a[nodes[r].index];
}
int find_R(int i)//找到初值为b[i]的数能接触到的新值的上界
{
int l=1,r=n,min_v=b[i];
while(r>l)
{
int mid= l+(r-l+1)/2;
if(nodes[mid].v-min_v < D)
l=mid;
else if(nodes[mid].v-min_v == D)
l=mid;
else
r=mid-1;
}
return a[nodes[l].index];
}
int main()
{
while(scanf("%d%d",&n,&D)==2&&n&&D)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&nodes[i].v);
b[i]=nodes[i].v;
nodes[i].index=i;
}
sort(nodes+1,nodes+n+1);
int max_num=1;
a[nodes[1].index]=1;
for(int i=2;i<=n;i++)//数值重新映射
{
if( nodes[i].v== nodes[i-1].v )
{
a[nodes[i].index]= max_num;
}
else
{
a[nodes[i].index]= ++max_num;
}
}
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++)
{
L[i]=find_L(i);
R[i]=find_R(i);
int temp =sum(1,R[i])-sum(1,L[i]-1)+sum(2, R[i])-sum(2,L[i]-1) ;//sum求和取差不一定是正确
temp = (temp+MOD)%MOD;//注意这里
add(2,a[i],temp);
add(1,a[i],1);
}
printf("%d\n",sum(2,n)%MOD);
}
return 0;
}
</span>
Sample Output
4