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