最长不下降子序列的个数
0.问题
- 1.计算一个序列的最长不下降子序列长度
- 2.并且给出这个序列中最长不下降子序列的个数
1.代码
如下所示。其中
- 1.len[i]存放以i为递增序列尾部元素的最长序列长度(注意是最长序列)
- 2.cnt[i]存放以i为递增序列尾部元素的最长序列个数(注意是最长序列)
#include<iostream>
using namespace std;
const int maxH = 155;
int main(){
int arr[maxH];
int n,m;
cin >> m;
while(m > 0){
cin >> n;
for(int i = 0;i< n;i++){
cin >> arr[i];
}
int res,maxLen = 0;
int len[maxH] , cnt[maxH];
for(int i = 0; i < n; i++){
//一定要注意这里的初始化
len[i] = cnt[i] = 1;
for(int j = 0; j < i ; j++){
if(arr[i] >= arr[j]){
if(len[i] == len[j] + 1)
//这行代码是否多余?
//不多余,因为,从cnt[j]也可以到达cnt[i],所以需要加上cnt[j]的 种类数
cnt[i] += cnt[j];
if(len[i] < len[j] + 1){
//如果len[i]是从len[j]过来的,就要将cnt[i]赋值为cnt[j],而不同于上面的 cnt[i] += cnt[j] 操作
len[i] = len[j] + 1;
cnt[i] = cnt[j];
}
}
}
if(maxLen == len[i])
res += cnt[i];
if(maxLen < len[i]){
maxLen = len[i];
res = cnt[i];
}
}
cout <<maxLen<<" "<< res << endl;
m--;
}
}
/*
测试用例
输入
3
9 10 1 9 8 7 6 3 4 6
3 100 70 102
6 40 37 23 89 91 12
输出
4 1
2 2
3 3
*/