//山谷序列
//最长上升子序列的变形题,时间复杂度O(n^2),空间复杂度O(n)
#include<iostream> #include<algorithm> #include<vector> using namespace std; int up_dp[1005]; //从左到右为上升子序列 int down_dp[1005];//从左到右为下降子序列 int valley_num(int n, const vector<int>& nums) { if (n < 2) return 0; memset(up_dp, 0, sizeof(up_dp)); memset(down_dp, 0, sizeof(down_dp)); int i, j; //down_dp[i]表示以nums[i]结尾的最长下降子序列的个数 for (i = 0; i < n; i++) { down_dp[i] = 1; for (j = 0; j < i; j++) if (nums[i] < nums[j]) down_dp[i] = max(down_dp[i], down_dp[j] + 1); } //up_dp[i]表示以nums[i]开头的最长上升子序列的个数 for (i = n - 1; i >= 0; i--) { up_dp[i] = 1; for (j = n - 1; j > i; j--) if (nums[i] < nums[j]) up_dp[i] = max(up_dp[i], up_dp[j] + 1); } //寻找最长的山谷序列 int res = 0; for(i=0;i<n;i++) for(j=i+1;j<n;j++) { if (nums[i] == nums[j]) { int cnt = min(down_dp[i], up_dp[j]); if (cnt > res) res = cnt; } } return 2 * res; } int main() { int t, n, i, j; cin >> t; while (t > 0) { cin >> n; vector<int> num(n,0); for (i = 0; i < n; i++) cin >> num[i]; cout << valley_num(n, num) << endl; t--; } //system("pause"); return 0; }
全部评论
(0) 回帖