【BZOJ】4361: isn
题解
可以想一下保留一个长度为k的不降序列方案数是\(f[k] (n - k)!\)
\(f[k]\)是有多少个长度为k的不降序列
我们去掉不合法的,一定是前一次操作的时候有一个长度为\(k + 1\)的不降序列,于是长度恰好为\(k\)的方案数就是
\(f[k](n - k)! - f[k + 1](n - k - 1)!(k + 1)\)
\(f[k]\)可以用树状数组维护
代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define pii pair<int,int>
#define pdi pair<db,int>
#define mp make_pair
#define pb push_back
#define enter putchar('\n')
#define space putchar(' ')
#define eps 1e-8
#define mo 974711
#define MAXN 2005
//#define ivorysi
using namespace std;
typedef long long int64;
typedef double db;
template<class T>
void read(T &res) {
res = 0;char c = getchar();T f = 1;
while(c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
res = res * 10 + c - '0';
c = getchar();
}
res *= f;
}
template<class T>
void out(T x) {
if(x < 0) {x = -x;putchar('-');}
if(x >= 10) {
out(x / 10);
}
putchar('0' + x % 10);
}
const int MOD = 1000000007;
int N;
int a[MAXN],val[MAXN],tot,fac[MAXN],h[MAXN],f[MAXN];
int tr[MAXN][MAXN];
int inc(int a,int b) {
return a + b >= MOD ? a + b - MOD : a + b;
}
int mul(int a,int b) {
return 1LL * a * b % MOD;
}
void update(int &x,int y) {
x = inc(x,y);
}
int lowbit(int x) {
return x & (-x);
}
void Insert(int k,int u,int v) {
while(u <= tot) {
update(tr[k][u],v);
u += lowbit(u);
}
}
int Query(int k,int u) {
int res = 0;
while(u > 0) {
update(res,tr[k][u]);
u -= lowbit(u);
}
return res;
}
void Solve() {
read(N);
for(int i = 1 ; i <= N ; ++i) {
read(a[i]);val[i] = a[i];
}
fac[0] = 1;
for(int i = 1 ; i <= N ; ++i) fac[i] = mul(fac[i - 1],i);
sort(val + 1,val + N + 1);
tot = unique(val + 1,val + N + 1) - val - 1;
for(int i = 1 ; i <= N ; ++i) {
int t = lower_bound(val + 1,val + tot + 1,a[i]) - val;
for(int j = i - 1 ; j >= 1 ; --j) {
int a = Query(j,t);
Insert(j + 1,t,a);
}
Insert(1,t,1);
}
for(int i = 1 ; i <= N ; ++i) {
update(f[i],Query(i,tot));
}
int ans = 0;
for(int i = N ; i >= 1 ; --i) {
update(ans,mul(f[i],fac[N - i]));
update(ans,MOD - mul(mul(f[i + 1],fac[N - i - 1]),i + 1));
}
out(ans);enter;
}
int main() {
#ifdef ivorysi
freopen("f1.in","r",stdin);
#endif
Solve();
return 0;
}