Find the nondecreasing subsequences(数状数组+离散化+dp)

Problem B

Time Limit : 10000/5000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 70   Accepted Submission(s) : 17
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思想的运用。这一点是非常不好理解的。就是还要注意求和会溢出,要求余mod。

代码:

#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define mod 1000000007
typedef long long ll;
using namespace std;
int n;
int c[100010],b[100010],t[100010];
struct node{
	int v;
	int id;
	bool operator<(const node&b)const
	{
		return v<b.v; 
	} 
}a[100010]; 
int lowbit(int x)
{
	return x&(-x);
}
int sum(int x)
{
	int res=0;
	while(x>0){
		res+=c[x];
		if(res>=mod)
		res%=mod;
		x-=lowbit(x);
	}
	return res;
}
void add(int i,int v)
{
	while(i<=n){
		c[i]+=v;
		if(c[i]>=mod)
		c[i]%=mod;
		i+=lowbit(i);
	}
}
int main()
{
	//ios::sync_with_stdio(false); 
	int i,j;
	while(scanf("%d",&n)!=EOF)
	{
		memset(b,0,sizeof(b));
		memset(c,0,sizeof(c));
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i].v); 
			a[i].id=i;
		}
		sort(a+1,a+n+1);
		b[a[1].id]=1;
		for(i=2;i<=n;i++) //离散化
		{
			if(a[i].v!=a[i-1].v)
			b[a[i].id]=i;
			else b[a[i].id]=b[a[i-1].id];	
		}
		for(i=1;i<=n;i++)  //核心点也是难理解的地方
		{
			t[i]=sum(b[i]);
			add(b[i],t[i]+1);
		}
		printf("%d\n",sum(n));
	}
	return 0;
} 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值