题意:求n个数中长度为m的上升子序列的个数。
析:很容易想到一个n的三次方的DP,dp[i][j]表示第 i 个数长度为 j 的LIS 有多少个,但是会TLE,因此必须优化,dp[i][j] = sum{dp[k][j-1] | a[i] > a[k]}
我们可以用树状数组优化,当然用线段树也OK,由于数据最大是1e9,所以必须进行离散化操作,然后再维护m个树状数组,复杂度是n*nlogn。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e3 + 10;
const int mod = 1e9 + 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}
int dp[maxn][maxn], sum[maxn][maxn];
int lowbit(int x){ return -x & x; }
void update(int i, int x, int val){
while(x < maxn){
sum[i][x] += val;
if(sum[i][x] >= mod) sum[i][x] -= mod;
x += lowbit(x);
}
}
int getSum(int i, int x){
int ans = 0;
while(x){
ans += sum[i][x];
if(ans >= mod) ans -= mod;
x -= lowbit(x);
}
return ans;
}
set<int> sets;
map<int, int> mp;
int a[maxn];
int main(){
int T; cin >> T;
for(int kase = 1; kase <= T; ++kase){
scanf("%d %d", &n, &m);
sets.clear(); mp.clear();
memset(sum, 0, sizeof sum);
for(int i = 0; i < n; ++i){
scanf("%d", a+i);
sets.insert(a[i]);
}
int cnt = 0;
for(set<int> :: iterator it = sets.begin(); it != sets.end(); ++it) mp[*it] = ++cnt;
for(int i = 0; i < n; ++i) a[i] = mp[a[i]];
memset(dp, 0, sizeof dp);
for(int i = 0; i < n; ++i)
for(int j = 1; j <= m; ++j){
if(j == 1) dp[i][j] = 1;
else {
dp[i][j] += getSum(j-1, a[i]-1);
if(dp[i][j] >= mod) dp[i][j] -= mod;
}
update(j, a[i], dp[i][j]);
}
int ans = 0;
for(int i = 0; i < n; ++i){
ans += dp[i][m];
if(ans >= mod) ans -= mod;
}
printf("Case #%d: %d\n", kase, ans);
}
return 0;
}