1002(dp+树状数组+离散化)

来源:互联网 发布:淘宝卖家客服常用语 编辑:程序博客网 时间:2024/05/21 17:06

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
31 2 3

Sample Output
7


题目大概:

求一个序列的子序列数。

思路:

用dp推出答案,用树状数组优化。

代码:


#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;int n;int b[100010];long long c[100010];int dp[100010];int pp=1000000007;struct poin{    int v,id;}a[100010];bool cmp(const poin a,const poin b){    return a.v<b.v;}int lowbit(int x){    return x&(-x);}int add(int x,int v){    while(x<=100001)    {        c[x]+=v;        c[x]=c[x]%pp;        x=x+lowbit(x);    }}long long sum(int x){    long long su=0;    while(x>0)    {        su+=c[x];        su=su%pp;        x-=lowbit(x);    }    return su;}int main(){        while(~scanf("%d",&n))        {         memset(c,0,sizeof(c));        for(int i=1;i<=n;i++)        {            scanf("%d",&a[i].v);            a[i].id=i;        }        sort(a+1,a+n+1,cmp);        b[a[1].id]=1;        int o=2;        for(int i=2;i<=n;i++)        {            if(a[i].v==a[i-1].v)b[a[i].id]=b[a[i-1].id];            else b[a[i].id]=o++;        }       for(int i=1;i<=n;i++)       {           dp[i]=sum(b[i])+1;           add(b[i],dp[i]);       }            printf("%d\n",sum(n));        }    return 0;}