一.原题链接:http://poj.org/problem?id=2533
二,O(n^2)无优化DP
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int MAX_SIZE = 50009; int dp[MAX_SIZE], arr[MAX_SIZE]; int n, m; int main() { //freopen("in.txt", "r", stdin); int N, i, j, ntemp; cin>>N; for(i = 0; i < N; i++){ scanf("%d", &arr[i]); dp[i] = 1; } for(i = 1; i < N; i++){ for(j = 0; j < i; j++){ if(arr[j] < arr[i]) dp[i] = max(dp[j] + 1, dp[i]); } } ntemp = -1; for(i = 0; i < N; i++) ntemp = max(dp[i], ntemp); cout<<ntemp; return 0; }
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> using namespace std; const int MAX_SIZE = 50009; const int INF = 1<<29; //dp[i]表示最大递增序列长度为i的最大元素; //如果有相同长度的最大递增序列,取最小的最大元素; int dp[MAX_SIZE], arr[MAX_SIZE]; int main() { //freopen("in1.txt", "r", stdin); int num, i, j, res, l, r, m; scanf("%d", &num); for(i = 1; i <= num; i++) scanf("%d", &arr[i]); dp[0] = -INF; dp[1] = arr[1]; res = 1; for(i = 2; i <= num; i++){ l = 1; r = res; while(l <= r && r >= 1){ m = (l + r)/2; if(dp[m] < arr[i]) l = m + 1; else r = m - 1; } dp[l] = arr[i]; if(res < l) res++; } printf("%d\n", res); }