hdu 2227(树状数组+dp)
Find the nondecreasing subsequences
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1844 Accepted Submission(s): 677
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] 以a[i]结尾的非递减子串的个数,可以知道 dp[i] = sum(dp[j])+1 (1<=j<i,a[j]<a[i]),这里a[j]<a[i]我们可以直接利用求解逆序数的原理得到,利用树状数组维护整个递推式。
#include <iostream> #include <stdio.h> #include <string.h> #include <stack> #include <vector> #include <algorithm> using namespace std; typedef long long LL; const int N = 100005; const int mod = 1000000007; int n; int a[N],b[N],c[N]; int lowbit(int x){ return x&(-x); } void update(int idx,int v){ for(int i=idx;i<=n;i+=lowbit(i)){ c[i]=(c[i]+v)%mod; } } int getsum(int idx){ int sum = 0; for(int i=idx;i>=1;i-=lowbit(i)){ sum = (sum+c[i])%mod; } return sum; } int main() { while(scanf("%d",&n)!=EOF){ memset(c,0,sizeof(c)); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); b[i] = a[i]; } sort(b+1,b+1+n); int ans = 0; for(int i=1;i<=n;i++){ int idx = lower_bound(b+1,b+1+n,a[i])-b; ans=getsum(idx); update(idx,ans+1); } printf("%d\n",getsum(n)); } return 0; }