题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3450
4 2 1 3 7 5
4
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <cstdio>
#include <algorithm>
#include <cmath>
const int N=1e5+100;
const int mod=9901;
using namespace std;
struct node
{
int v,id;
}a[N];
bool cmp(node a,node b)
{
return a.v<b.v;
}
int n,d,c[N],b[N];
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int d)
{
while(x<=n)
{
c[x]+=d;
if(c[x]>mod)c[x]%=mod;
x+=lowbit(x);
}
}
int getsum(int x)
{
int ans=0;
while(x>0)
{
ans+=c[x];
if(ans>mod)ans%=mod;
x-=lowbit(x);
}
return ans;
}
int find(int x)
{
if(x>=a[n].v)return n;
if(x<a[1].v)return 0;
int l=1,r=n,ret=0;
while(l<=r)
{
int mid=(l+r)/2;
if(x>=a[mid].v)
{
ret=mid;
l=mid+1;
}
else
r=mid-1;
}
return ret;
}
int main()
{
while(scanf("%d%d",&n,&d)!=EOF)
{
memset(c,0,sizeof(c));
memset(b,0,sizeof(b));
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].v);
a[i].id=i;
}
sort(a+1,a+1+n,cmp);
for(int i=1;i<=n;i++)b[a[i].id]=i;
int sum=0;
for(int i=1;i<=n;i++)
{
int p=find(a[b[i]].v+d);
int q=find(a[b[i]].v-d-1);
int temp=getsum(p)-getsum(q);
temp=(temp+mod)%mod;
sum=(sum+temp)%mod;
update(b[i],temp+1);
}
printf("%d\n",sum);
}
return 0;
}
原文地址:http://blog.csdn.net/liusuangeng/article/details/39552893