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
求上升子序列的个数。这题一开始的想法是用DP,很容易的得到这样的状态转移方程。
设dp[a[i]]为以a[i]为结尾的上升子序列个数。
则
dp[a[j]]=sum( dp[a[i]] )+1; (i>=1 && i<j && a[j]>=a[i])
因为a[i]<2^31,所以要先离散化一下。
但是n的范围1 <= n <= 100000,这样做,无疑是不行的。
根据DP的状态转移方程,可联想到求逆序数。
使用树状数组。
#include <stdio.h>
#include <algorithm>
#include <string.h>
#define MOD 1000000007
#define N 100005
using namespace std;
typedef struct{
long long key;
long long value;
}Node;
Node a[N];
long long c[N];
long long re[N];
long long n;
long long lowbit(long long x)
{
return x&-x;
}
long long sum(long long x)
{
long long ret=0;
while(x>0)
ret=(ret+c[x])%MOD,x-=lowbit(x);
return ret;
}
void add(long long x,long long d)
{
while(x<=n)
{
c[x]=(c[x]+d)%MOD;x+=lowbit(x);
}
}
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
int main()
{
while(scanf("%I64d",&n)>0)
{
for(long long i=1;i<=n;i++)
scanf("%I64d",&a[i].value),a[i].key=i;
sort(a+1,a+n+1,cmp);
re[a[1].key]=1;
int cnt=1;
for (long long i = 2; i <= n; i++)
{
if(a[i].value!=a[i-1].value)
cnt++;
re[a[i].key]=cnt;
}
memset(c,0,sizeof(c));
for (long long i = 1; i <= n; i++)
{
int temp=sum(re[i]);
add(re[i],temp+1);
}
printf("%I64d\n", sum(n));
}
return 0;
}