Idea: Create a dp[i] array, where i represents the last element (and the largest element) in a subsequence. Then loop twice, the time complexity is O(n^2), see the AC code below for details
Example: POJ 2533
Code:
#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <cstdlib> #include <cstring> #include <vector> #include <list> #include <map> #include <stack> #include <queue> using namespace std; #define ll long long int dp[1111]; int a[1111]; intmain() { int n ; while(cin >> n) { for(int i = 0;i < n;i++) cin >>a[i]; for(int i = 0;i < n;i++) dp[i] = 1;//Each sequence that ends with itself has at least one sequence of increasing length for (int i = 0; i < n; i++)//The first layer of loop, find the maximum ascending sequence with the i-th element as the last for (int j = i+1; j < n; j++)//The second layer of loop, refresh the sequence later if(a[i] < a[j])//For example, if the array is 1 4 3 5, a[i] = 3, then the maximum subsequence ending with i is 1 3, a[ j] = 5, since 3 < 5, a[j] = a[i]+1, so the largest subsequence of a[j] is 1 3 5 dp[j] = max(dp[j],dp[i]+1); int years = 0; for(int i = 0;i < n;i++) ans = max(ans,dp[i]);//Find the largest one of the largest subsequences ending in a[i] cout << ans <<endl; } return 0; }
Note: This is easy to mix with the maximum common subsequence. At first, I directly output the last element in the dp array. Later, I found that it was wrong. Let me give an example.
Array 1 3 4 5 2
The largest is dp[3], which is the sequence 1 3 4 5
And dp[4] is the sequence 1 2
In the maximum ascending sequence, dp[i] represents the ascending sequence with the element at this position as the maximum value
In finding the largest common sequence, the last element of dp represents the largest common sequence size from front to back