题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2227

Find the nondecreasing subsequences

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 476    Accepted Submission(s): 186


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[a[j]]=sum( dp[a[i]] )+1;          (i>=1 && i<j && a[j]>=a[i]) //单独的a[j]也算一个

因为a[i]<2^31,所以要先离散化一下,把所有数映射到1---n这个区间内。

code:

View Code
 1 # include<stdio.h>
2 # include<string.h>
3 # include<stdlib.h>
4 # define N 100005
5 # define Mod 1000000007
6 int s[N],n,a[N];
7 __int64 dp[N];
8 int cmp(const void *a,const void *b)
9 {
10 return *(int *)a - *(int *)b;
11 }
12 int find(int x)
13 {
14 int left,right,mid,ans;
15 left=1;
16 right=n;
17 while(right>=left)
18 {
19 mid=(right+left)/2;
20 if(a[mid]==x) {ans=mid;right=mid-1;}
21 else if(a[mid]>x) right=mid-1;
22 else left=mid+1;
23 }
24 return ans;
25 }
26 __int64 query(int i)
27 {
28 __int64 count;
29 count=0;
30 while(i>=1)
31 {
32 count+=dp[i];
33 count%=Mod;
34 i-=i&(-i);
35 }
36 return count;
37 }
38 void insert(int i,__int64 ans)
39 {
40 while(i<=n)
41 {
42 dp[i]+=ans;
43 dp[i]%=Mod;
44 i+=i&(-i);
45 }
46 }
47 int main()
48 {
49 int i,ans;
50 __int64 sum,num;
51 while(scanf("%d",&n)!=EOF)
52 {
53 for(i=1;i<=n;i++)
54 {
55 scanf("%d",&s[i]);
56 a[i]=s[i];
57 }
58 qsort(a+1,n,sizeof(a[1]),cmp);
59 memset(dp,0,sizeof(dp));
60 sum=0;
61 for(i=1;i<=n;i++)
62 {
63 ans=find(s[i]);
64 num=query(ans)+1;
65 insert(ans,num);
66 sum+=num;
67 sum%=Mod;
68 }
69 printf("%I64d\n",sum%Mod);
70 }
71 return 0;
72 }

 

 

posted on 2011-10-30 09:32  奋斗青春  阅读(1420)  评论(3编辑  收藏  举报