吐吐槽吧:本来思路完全对了,但是那个二分查找搞错了,我还以为一个就可以了,结果查找上界和下界分别要一个查找函数(WA时就看了一下别人的代码,发现别人都是用两个查找函数的,模仿别人写的查找函数),自己得好好揣摩揣摩。。。
还有就是最后的结果可能是负数。。。因为get_sum的值是小于9901的,而N的值可大于9901
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 5 const int mod = 9901; 6 const int maxn = 100000 + 100; 7 8 int a[maxn]; 9 int val[maxn]; 10 int c[maxn]; 11 int N,D,num; 12 13 int binary_find1(int x,int l,int r) 14 { 15 int ans = r; 16 while(l <= r) 17 { 18 int mid = (l + r) / 2; 19 if(val[mid] <= x) l = mid + 1,ans = mid; 20 else r = mid - 1; 21 } 22 23 return ans; 24 } 25 26 int binary_find2(int x,int l,int r) 27 { 28 int ans = l; 29 while(l <= r) 30 { 31 int mid = (l + r) / 2; 32 if(val[mid] < x) l = mid + 1; 33 else r = mid - 1,ans = mid; 34 } 35 return ans; 36 } 37 int get_sum(int x) 38 { 39 int sum = 0; 40 while(x > 0) 41 { 42 sum += c[x]; 43 sum = sum % mod; 44 x -= (x & (-x)); 45 } 46 47 return sum; 48 } 49 50 void insert(int x,int v) 51 { 52 while(x < num) 53 { 54 c[x] += v; 55 c[x] = c[x] % mod; 56 x += (x & (-x)); 57 } 58 } 59 60 int main() 61 { 62 while(scanf("%d%d",&N,&D) == 2) 63 { 64 for(int i = 1;i <= N;i ++) 65 { 66 scanf("%d",&a[i]); 67 val[i] = a[i]; 68 } 69 std::sort(val + 1,val + N + 1); 70 num = 2; 71 for(int i = 2;i <= N; i ++) 72 { 73 if(val[i] != val[i -1]) 74 val[num ++] = val[i]; 75 } 76 memset(c,0,sizeof(c)); 77 for(int i = 1;i <= N;i ++) 78 { 79 int k = binary_find1(a[i],1,num - 1); 80 int x = binary_find1(a[i]+ D,1,num -1); 81 int y = binary_find2(a[i] - D,1,num-1); 82 int ans = 1; 83 ans += get_sum(x); 84 ans -= get_sum(y - 1); 85 ans %= mod; 86 insert(k,ans); 87 } 88 89 printf("%d\n",((get_sum(num-1) - N)%mod +mod)%mod); 90 } 91 92 return 0; 93 }