Find the nondecreasing subsequences
Time Limit : 10000/5000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 2 Accepted Submission(s) : 2
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
题意:
给定序列集合 求有多少个非递减子序列。
思路:每多加一个数的方法数是之前所有小于等于它的方法数之和加一,数据较大所以 所以需要 离散化。然后用树状数组维护。
code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
#define mod 1000000007
#define maxn 100005
#define lowbit(x) (x&(x^(x-1)))
using namespace std;
struct node
{
int key;///保存原序列的次序,离散化后用来唯一代表这个val值
ll val;///序列的大小
};
node a[maxn];
int c[maxn];
int b[maxn];
int n;
int sum(int p)
{
ll ans=0;
while(p>0){
ans=(ans+c[p])%mod;
p-=lowbit(p);
}
return ans;
}
void update(int p,int x)
{
while(p<=n){
c[p]=(c[p]+x)%mod;
p+=lowbit(p);
}
}
bool cmp(node a,node b)
{
return a.val<b.val;
}
int main()
{
while(~scanf("%d",&n)){
for(int i=1;i<=n;i++){
scanf("%lld",&a[i].val);
a[i].key=i;
}
sort(a+1,a+n+1,cmp);
b[ a[1].key ]=1;
int cnt=1;
for(int i=2;i<=n;i++){
if(a[i].val!=a[i-1].val)
cnt++;
b[a[i].key]=cnt;///cnt 用来代表它的大小
}
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++){
int temp=sum(b[i]);
update(b[i],temp+1);
}
printf("%d\n",sum(n));
}
return 0;
}