Find the nondecreasing subsequences
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1791 Accepted Submission(s): 655
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
题意就是让我们求出所有升序排列的子序列的个数,很容易想到的是用dp来做,一层一层的叠上去,但是问题来了,n可能会达到100000,如果dp的话,肯定会面临超时的危险,所以这里的dp我们就用树状数组推上去。首先我们记录每一个的位置,然后再对其进行按大小排序,每一个元素就等于排在其前面的所有位置也在其前面的和+1,用树状数组叠上去就好。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100000+10;
const int MOD = 1000000007;
int n,c[maxn];
struct node
{
int value,index;
}a[maxn];
int Lowbit(int x)
{
return x&(-x);
}
void update(int x,int detal)
{
while(x <= n)
{
c[x] = (c[x]+detal)%MOD;
x += Lowbit(x);
}
}
int getsum(int x)
{
int sum = 0;
while(x > 0)
{
sum = (sum+c[x])%MOD;
x -= Lowbit(x);
}
return sum;
}
int cmp(node a,node b)
{
if(a.value == b.value) return a.index < b.index;
else return a.value < b.value;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i].value);
a[i].index = i;
}
sort(a+1,a+n+1,cmp);
int tmp = 0;
for(int i=1; i<=n; i++)
{
tmp = getsum(a[i].index)+1;
tmp %= MOD;
update(a[i].index,tmp);
}
printf("%d\n",getsum(n));
}
return 0;
}