Find the nondecreasing subsequences

来源:互联网 发布:淘宝分销平台系统 编辑:程序博客网 时间:2024/06/16 12:17

roblem 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
31 2 3
 

Sample Output
7
 

Author
8600
 


Recommend
lcy




保存输入的数和序号在结构体中,然后按数的大小排序。

之后b数组保存排序后的顺序。相当用树状数组求逆序数。

for i=1:n

     b[i]

按输入的原来顺序(b[i]保存排序后的顺序)

更新树状数组。统计出比他小的数总共有几个。最后sum[n]为所求。

#include<iostream>
#include<stdio.h>
#include<memory.h>
#include<algorithm>
using namespace std;
#define MAX  100005
#define BASE 1000000007
struct node{
   int val,id;
}a[MAX];


bool cmp(node a,node b)
{
   return a.val<b.val;
}


int b[MAX],c[MAX],s[MAX],n;


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


void update(int i,int x)
{
   while(i<=n)
   {
       s[i]+=x;
  if(s[i]>=BASE)
  s[i]%=BASE;
  i+=lowbit(i);
   
   }
}


int sum(int i)
{
   int sum=0;
   while(i>0)
   {
      sum+=s[i];
 if(sum>=BASE)
 sum%=BASE;
 i-=lowbit(i);
   
   }
   return sum;
 
}
int main()
{
   int i,res;
   while(scanf("%d",&n)!=EOF)
   {
      memset(b,0,sizeof(b));
 memset(s,0,sizeof(s));
 for(i=1;i<=n;i++)
 {
    scanf("%d",&a[i].val);
    a[i].id=i;
 }
 sort(a+1,a+n+1,cmp);
 b[a[1].id]=1;
 for(i=2;i<=n;i++)
 {
    if(a[i].val!=a[i-1].val)
b[a[i].id]=i;
else b[a[i].id]=b[a[i-1].id];


 }
 res=0;
 for(i=1;i<=n;i++)
 {
    c[i]=sum(b[i]);
update(b[i],c[i]+1);
 }
 printf("%d\n",sum(n));
   }
   return 0;
}


原创粉丝点击