BestCoder16 1002.Revenge of LIS II(hdu 5087) 解题报告
生活随笔
收集整理的這篇文章主要介紹了
BestCoder16 1002.Revenge of LIS II(hdu 5087) 解题报告
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=5087
題目意思:找出第二個最長遞增子序列,輸出長度。就是說,假如序列為 1 1 2,第二長遞增子序列是1 2(下標為2 3),而第一長遞增子序列也是(下標為 1 3)。
? ? 我一開始天真的以為,還是利用求最長遞增子序列的算法啦,第二長不就是對dp 數組sort完后(從小到大)的dp[cnt-1] 啦,接著就呵呵啦~~~~= =
? ? 題解說,要加多一個 dp 數組,以便對當前下標值為 i 的數 a[i] 為結尾求出第二條dp序列,如果長度一樣就直接那個長度了,否則是長度減 1。一直對每個數這樣處理,處理到序列最后一個數就是答案了。
? ? 以下是看別人的。設 dp[i][0] 表示以a[i]這個數為結尾的最長遞增子序列的長度,dp[i][1] 表示以a[i]這個數為結尾的第二長遞增子序列的長度(可能為dp[i][0],也可能是dp[i][0]-1)
? ? 然后把每個數的兩個dp值放進ans數組中,sort之后,答案就為ans[cnt-2]。
? ?
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <algorithm> 6 using namespace std; 7 8 const int N = 1000 + 10; 9 10 int a[N], ans[2*N]; 11 int dp[N][2]; 12 13 int main() 14 { 15 int T, n; 16 #ifndef ONLINE_JUDGE 17 freopen("input.txt", "r", stdin); 18 #endif 19 while (scanf("%d", &T) != EOF) 20 { 21 while (T--) 22 { 23 scanf("%d", &n); 24 for (int i = 1; i <= n; i++) 25 scanf("%d", &a[i]); 26 memset(dp, 0, sizeof(dp)); 27 int cnt = 0; 28 for (int i = 1; i <= n; i++) 29 { 30 dp[i][0] = 1; 31 for (int j = 1; j < i; j++) 32 { 33 if (a[j] < a[i]) 34 { 35 int x = dp[j][0] + 1; 36 int y = dp[j][1] + 1; 37 38 if (x > dp[i][0]) 39 swap(x, dp[i][0]); 40 dp[i][1] = max(x, dp[i][1]); 41 dp[i][1] = max(y, dp[i][1]); 42 } 43 } 44 ans[cnt++] = dp[i][0]; 45 ans[cnt++] = dp[i][1]; 46 } 47 sort(ans, ans+cnt); 48 printf("%d\n", ans[cnt-2]); 49 } 50 } 51 return 0; 52 }?
轉載于:https://www.cnblogs.com/windysai/p/4075008.html
總結
以上是生活随笔為你收集整理的BestCoder16 1002.Revenge of LIS II(hdu 5087) 解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 802.11介绍
- 下一篇: [Python]ConfigParser