Counting Sequences
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/65536 K (Java/Others)Total Submission(s): 1906 Accepted Submission(s): 647
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
Sample Output
4
Source
题目分析:对原序列排序,将他们的新序位当作大小的值,作为离散化操作 ,然后对应序位获得序位之前和当前位差值小于d的点,他们的所有符合条件序列的和即为当前点序列个数,那么相加即可,查找区间,利用二分查找,id可以通过利用结构体记录原始id得到
注意结果可能为负,取模时做一下处理
注意结果可能为负,取模时做一下处理
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define MAX 100007
#define MOD 9901
using namespace std;
int n,m,cnt;
struct Point
{
int a,id;
bool operator < ( const Point & x ) const
{
if ( a == x.a ) return id < x.id;
return a < x.a;
}
}p[MAX];
int c[MAX];
int b[MAX];
int d[MAX];
int lowbit ( int x )
{
return x&-x;
}
void add ( int x , int v )
{
while ( x <= n )
{
c[x] = ( c[x] + v ) %MOD;
x += lowbit(x);
}
}
int sum ( int x )
{
int ret = 0;
while ( x )
{
ret = (ret + c[x])%MOD;
x -= lowbit(x);
}
return ret;
}
int find_r ( int x , int v )
{
int left = 1 , right = n , mid;
while ( left != right )
{
mid = (left+right+1) >>1;
if ( p[mid].a-x > v ) right = mid-1;
else left = mid;
}
return left;
}
int find_l ( int x , int v )
{
int left = 1 , right = n , mid;
while ( left != right )
{
mid = left + right >> 1;
if ( x - p[mid].a > v ) left = mid+1;
else right = mid;
}
return left;
}
int main ( )
{
while ( ~scanf ( "%d%d" , &n , &m ) )
{
memset ( c , 0 , sizeof ( c ) );
for ( int i = 1 ; i <= n ; i++ )
{
scanf ( "%d" , &p[i].a );
p[i].id = i;
b[i] = p[i].a;
}
cnt = 0;
sort ( p+1 , p+n+1 );
for ( int i = 1 ; i <= n ; i++ )
d[p[i].id] = i;
int ans = 0;
for ( int i = 1 ; i <= n ; i++ )
{
int l = find_l ( b[i] , m );
int r = find_r ( b[i] , m );
int temp = (sum(r) - sum(l-1))%MOD;
ans = ( ans + temp )%MOD;
add ( d[i] , temp+1 );
}
printf ( "%d\n" , (ans%MOD+MOD)%MOD );
}
}