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给你一个有序序列, 求有多少个不下降子序列,结果对 10^9+7 取模
这道题目的数据比较大 1 <= n <= 100000 0 <= si <= 2^31 如果数据比较小直接 DP就可以解决了
如何转换成树桩数组求解? 什么是离散化?关于这题如何离散化?
这题求的是不下降子序列的个数。
也就是说符合要求的序列元素的后面的一个的值总是大于或等于前一个元素的【废话一句可以忽略Orz那么我们可以先对输入的元素 a[i] 按照从小到大做一个排序处理。
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const ll INF=1e18;
const int maxn = 100000+10;
const int mod = 1000000007;
int c[maxn];
int n;
struct Node{
int value; //对应元素的值
int index; //元素初始编号
}node[maxn];
bool cmp(Node a, Node b) //先按元素值从小到大排序,元素值一样,再按照 编号从小到大排序
{
if(a.value == b.value) return a.index < b.index;
else return a.value < b.value;
}
int lowbit(int x)
{
return x&(-x);
}
void add(int index, int value) //快速更新 :节点 index 增加 value
{
while(index <= n)
{
c[index] = (c[index]+value) % mod;
index += lowbit(index);
}
}
int sum(int index) //快速求前缀和
{
int ret = 0;
while(index > 0)
{
ret = (ret+c[index])%mod;
index -= lowbit(index);
}
return ret; //勿忘
}
int main()
{
while(scanf("%d", &n) != EOF)
{
memset(node, 0, sizeof(node));
memset(c, 0, sizeof(c));
for(int i = 1; i <= n; i++)
{
scanf("%d", &node[i].value);
node[i].index = i;
}
sort(node+1, node+n+1, cmp); //排序
int tmp = 0;
for(int i = 1; i <= n; i++)
{
tmp = sum(node[i].index)+1; //求处理过后的前缀和相当于思路中的 num[index]
tmp %= mod;
add(node[i].index, tmp); // 相当于思路中给 num[index]增加 tmp
}
printf("%d\n", sum(n));
}
return 0;
}