HDU 2227 Find the nondecreasing subsequences

本文介绍了一种高效算法来解决寻找序列中上升子序列的问题。通过使用树状数组优化动态规划过程,解决了大规模数据输入下的性能瓶颈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

B - B
Time Limit:5000MS    Memory Limit:32768KB    64bit IO Format:%I64d & %I64u

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值