Find the nondecreasing subsequences
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1545 Accepted Submission(s): 558
Problem Description
How many nondecreasing subsequences can you find in the sequence S = {s1, s2, s3, ...., sn} ? For example, we assume that S = {1, 2, 3}, and you can find seven nondecreasing subsequences, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}.
Input
The input consists of multiple test cases. Each case begins with a line containing a positive integer n that is the length of the sequence S, the next line contains n integers {s1, s2, s3, ...., sn}, 1 <= n <= 100000, 0 <= si <= 2^31.
Output
For each test case, output one line containing the number of nondecreasing subsequences you can find from the sequence S, the answer should % 1000000007.
Sample Input
3 1 2 3
Sample Output
7
Author
8600
Recommend
题目分析:
枚举以每个点为结尾的上升子序列的个数,再求和
每个点的上升子序列的个数等于当前点前面所有不比当前点大的点所有的上升子序列的个数之和
那么利用树状数组维护这个前缀和即可,因为取值范围大
先排序,保证值从小到大,树状数组维护位置的前缀和即可,用到了转换的思想
枚举以每个点为结尾的上升子序列的个数,再求和
每个点的上升子序列的个数等于当前点前面所有不比当前点大的点所有的上升子序列的个数之和
那么利用树状数组维护这个前缀和即可,因为取值范围大
先排序,保证值从小到大,树状数组维护位置的前缀和即可,用到了转换的思想
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define MAX 100007
#define MOD 1000000007
using namespace std;
int n;
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 tid[MAX];
int c[MAX];
int cnt;
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 main ( )
{
while ( ~scanf ( "%d" , &n ) )
{
cnt = 1;
memset ( c , 0 , sizeof ( c ) );
for ( int i = 0 ; i < n ; i++ )
{
scanf ( "%d" , &p[i].a );
p[i].id = i+1;
}
sort ( p , p+n );
/*tid[p[0].id] = cnt++;
for ( int i = 1 ; i < n ; i++ )
if ( p[i].a != p[i-1].a ) tid[p[i].id] = cnt++;
else tid[p[i].id] = cnt;*/
int ans = 0;
for ( int i = 0 ; i < n ; i++ )
{
int temp = (sum ( p[i].id )+1)%MOD;
ans = ( ans + temp ) %MOD;
add ( p[i].id , temp );
}
printf ( "%d\n" , ans );
}
}