hdu 2227(树状数组优化dp)

本文介绍了一种使用树状数组优化动态规划算法的方法,用于解决在一个整数序列中寻找所有非递增子序列的问题,并提供了一个具体的C++实现案例。

Find the nondecreasing subsequences

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

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
 
解题思路:dp[i]表示前i个数里面非递增子序列个数,则dp[i] = sum{dp[k]} + 1,a[k] <= a[i],+1表示自己单独也是一个非递增序列。O(n²)超时,这里需要用树状数组优化它。具体的做法就不多说了,前面做过几个了。排序,离散化即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
using namespace std;

const int maxn = 100005;
const int mod = 1e9+7;
int n,tree[maxn<<1],a[maxn],dp[maxn];
set<int> Set;
map<int,int> Map;

int lowbit(int x)
{
	return x & -x;
}

void update(int x,int c)
{
	for(int i = x; i <= n; i += lowbit(i))
		tree[i]  = (tree[i] + c) % mod;
}

int getsum(int x)
{
	int sum = 0;
	for(int i = x; i > 0; i -= lowbit(i))
		sum = (sum + tree[i]) % mod;
	return sum;
}

int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		Set.clear();
		Map.clear();
		for(int i = 1; i <= n; i++)
		{
			scanf("%d",&a[i]);
			Set.insert(a[i]);
		}
		int cnt = 0;
		for(set<int>::iterator it = Set.begin(); it != Set.end(); it++)
			Map[*it] = ++cnt; 
		memset(tree,0,sizeof(tree));
		int ans = 0;
		for(int i = 1; i <= n; i++)
		{
			int tmp = getsum(Map[a[i]]);
			dp[i] = (tmp + 1) % mod;
			update(Map[a[i]],dp[i]);
		}
		for(int i = 1; i <= n; i++)
			ans = (ans + dp[i]) % mod;
		printf("%d\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值