题意 : 求一个数列的所有严格递增子序列的数量。
思路 : 定义一个状态:dp[i]表示第i个位置的数a[i]为这个序列的结尾的所有递增子序列数量,dp[i] = ∑dp[k] (a[i] > a[k] && i > k),这样可以用一个线段树来维护寻找[min, a[i] - 1]所有的dp[k]的总和,而因为输入的|a[]| < 2 ^ 32 - 1, 所以先离散化处理。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100005;
const int mod = 1000000007;
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
struct read
{
int v, p;
}q[maxn], p[maxn];
int ls[maxn], a[maxn];
int dp[maxn<<2], n;
int cmp(read a, read b)
{
return a.v < b.v;
}
void init_input()
{
for (int i = 1; i <= n; i++)
{
scanf("%d", &q[i].v);
q[i].p = i;
}
sort(q + 1, q + 1 + n, cmp);
ls[1] = q[1].v; p[1].v = 1; p[1].p = q[1].p;
for (int i = 2; i <= n; i++)
{
if (q[i].v == ls[i-1])
{
p[i].v = p[i-1].v;
}
else
{
p[i].v = p[i-1].v + 1;
}
ls[i] = q[i].v;
p[i].p = q[i].p;
}
for (int i = 1; i <= n; i++)
{
a[p[i].p] = p[i].v;
}
}
void pushup(int rt)
{
dp[rt] = dp[rt<<1] + dp[rt<<1|1];
dp[rt] %= mod;
}
void build(int rt, int l, int r)
{
if (l == r)
{
dp[rt] = 0;
return ;
}
int mid = (l + r) >> 1;
build(lson); build(rson);
pushup(rt);
}
void update(int rt, int l, int r, int loc, int addv)
{
if (l == r)
{
dp[rt] += addv;
dp[rt] %= mod;
return ;
}
int mid = (l + r) >> 1;
if (mid >= loc)update(lson, loc, addv);
else update(rson, loc, addv);
pushup(rt);
}
int query(int rt, int l, int r, int L, int R)
{
if (r < l || l > R)return 0;
if (l >= L && r <= R)
{
return dp[rt];
}
int mid = (l + r) >> 1, res = 0;
if (mid >= L)res += query(lson, L, R); res %= mod;
if (R > mid) res += query(rson, L, R); res %= mod;
return res;
}
void debug()
{
for (int i = 1; i <= n; i++)printf("%d ", a[i]);
printf("\n");
}
int main()
{
int T;
scanf("%d", &T);
for (int cas = 1; cas <= T; cas++)
{
scanf("%d", &n);
init_input();
//debug();
build(1, 1, n);
int res = 0;
for (int i = 1; i <= n; i++)
{
int tt = query(1, 1, n, 1, a[i] - 1) + 1;
res += tt; res %= mod;
update(1, 1, n, a[i], tt);
}
printf("Case %d: %d\n", cas, res);
}
return 0;
}