您的位置:首页 > 产品设计 > UI/UE

HDU 2227 Find the nondecreasing subsequences

2015-08-15 21:29 411 查看
B - B
Time Limit:5000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
SubmitStatusPracticeHDU
2227

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,很容易的得到这样的状态转移方程。

设dp[a[i]]为以a[i]为结尾的上升子序列个数。



dp[a[j]]=sum( dp[a[i]] )+1; (i>=1 && i<j && a[j]>=a[i])

因为a[i]<2^31,所以要先离散化一下。

但是n的范围1 <= n <= 100000,这样做,无疑是不行的。

根据DP的状态转移方程,可联想到求逆序数。

使用树状数组。

#include <stdio.h>
#include <algorithm>
#include <string.h>
#define MOD 1000000007
#define N 100005
using namespace std;
typedef struct{
long long key;
long long value;
}Node;
Node a
;
long long c
;
long long re
;
long long n;
long long lowbit(long long x)
{
return x&-x;
}
long long sum(long long x)
{
long long ret=0;
while(x>0)
ret=(ret+c[x])%MOD,x-=lowbit(x);
return ret;
}
void add(long long x,long long d)
{
while(x<=n)
{
c[x]=(c[x]+d)%MOD;x+=lowbit(x);
}
}
bool cmp(Node a,Node b)
{
return a.value<b.value;
}
int main()
{
while(scanf("%I64d",&n)>0)
{
for(long long i=1;i<=n;i++)
scanf("%I64d",&a[i].value),a[i].key=i;
sort(a+1,a+n+1,cmp);
re[a[1].key]=1;
int cnt=1;
for (long long i = 2; i <= n; i++)
{
if(a[i].value!=a[i-1].value)
cnt++;
re[a[i].key]=cnt;
}
memset(c,0,sizeof(c));
for (long long i = 1; i <= n; i++)
{
int temp=sum(re[i]);
add(re[i],temp+1);
}
printf("%I64d\n", sum(n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: