题目大意:给定一个长度为n的序列,问其共有多少个长度为m的子序列
思路:
用dp【i】【j】表示包含i个元素、第j个元素结尾的上升子序列的数量
刚开始三重循环会超时:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int mod = 1000000007;
int a[1010], dp[1010][1010];
int main()
{
int T, n, m, flag = 0; scanf("%d", &T);
while (T--) {
scanf("%d %d", &n, &m);
memset(a, 0, sizeof(a));
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= n; i++) dp[1][i] = 1;
for (int i = 2; i <= m; i++) {
for (int j = i; j <= n; j++) {
for (int k = 1; k < j; k++) {
if (a[k] < a[j]) {
dp[i][j] = (dp[i][j] + dp[i - 1][k]) % mod;
}
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
ans = (ans + dp[m][i]) % mod;
}
printf("Case #%d: %d\n", ++flag, ans);
}
return 0;
}
然后借鉴了别人的树状数组 + dp的思路:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int mod = 1000000007;
int n, m, a[1010], b[1010], dp[1010][1010];
int lowbit(int x) { return x & (-x); }
int sum(int x, int y) {
int temp = 0;
while (x > 0) {
temp = (temp + dp[x][y]) % mod;
x -= lowbit(x);
}
return temp;
}
void add(int x, int y, int d) {
while (x <= n) {
dp[x][y] = (dp[x][y] + d) % mod;
x += lowbit(x);
}
}
int main()
{
int T, flag = 0; scanf("%d", &T);
while (T--) {
memset(dp, 0, sizeof(dp));
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
b[i] = a[i];
}
sort(b + 1, b + 1 + n);
for (int i = 1; i <= n; i++) {
a[i] = lower_bound(b + 1, b + 1 + n, a[i]) - b;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= min(i + 1, m); j++) {
if (j == 1) add(a[i], 1, 1);
else {
int temp = sum(a[i] - 1, j - 1);
add(a[i], j, temp);
}
}
}
printf("Case #%d: %d\n", ++flag, sum(n, m));
}
return 0;
}