最长上升子序列中对于数ipt[i],向前遍历,当数ipt[j]小于ipt[i] 则ipt[j]可作为上升序列中ipt[i]的前一个数字
dp[i] = max{ dp[j] + 1 | j < i && ipt[j] < ipt[i]}
若现在有两个状态a,b 满足dp[a] = dp[b]且 ipt[a] < ipt[b]
则对于后面的状态dp[a]更优 因为若ipt[i] > dp[b] 则必然ipt[i] > dp[a],反之若ipt[i] > dp[a] 却不一定满足ipt[i] > dp[b]
所以若只保存状态a 那么也不会丢失最优解
那么对于相同dp值,只需保留ipt最小的一个
则 ipt值(dp=1) < ipt值(dp=2) < ipt值(dp=3).....
即此序列有序
比如 1 6 2 3 7 5
dp 1 2 2 3 4 4
当计算2时 发现dp=2的ipt值为6 则6可替换为2
同理 1 (6) 2 3 (7) 5
dp 1 2 3 4
这样,计算时维护一个序列即可
//#pragma comment(linker, "/STACK:102400000,102400000") //HEAD #include <cstdio> #include <cstring> #include <vector> #include <iostream> #include <algorithm> #include <queue> #include <string> #include <set> #include <stack> #include <map> #include <cmath> #include <cstdlib> using namespace std; //LOOP #define FE(i, a, b) for(int i = (a); i <= (b); ++i) #define FED(i, b, a) for(int i = (b); i>= (a); --i) #define REP(i, N) for(int i = 0; i < (N); ++i) #define CLR(A,value) memset(A,value,sizeof(A)) //STL #define PB push_back //INPUT #define RI(n) scanf("%d", &n) #define RII(n, m) scanf("%d%d", &n, &m) #define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k) #define RS(s) scanf("%s", s) typedef long long LL; const int INF = 0x3f3f3f3f; const int MAXN = 1010; #define FF(i, a, b) for(int i = (a); i < (b); ++i) #define FD(i, b, a) for(int i = (b) - 1; i >= (a); --i) #define CPY(a, b) memcpy(a, b, sizeof(a)) #define FC(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++) #define EQ(a, b) (fabs((a) - (b)) <= 1e-10) #define ALL(c) (c).begin(), (c).end() #define SZ(V) (int)V.size() #define RIV(n, m, k, p) scanf("%d%d%d%d", &n, &m, &k, &p) #define RV(n, m, k, p, q) scanf("%d%d%d%d%d", &n, &m, &k, &p, &q) #define WI(n) printf("%d\n", n) #define WS(s) printf("%s\n", s) #define sqr(x) (x) * (x) typedef vector <int> VI; typedef unsigned long long ULL; const double eps = 1e-10; const LL MOD = 1e9 + 7; int ipt[1010], dp[1010], a[1010]; int main() { int n; while (~RI(n)) { REP(i, n) RI(ipt[i]); REP(i, n) dp[i] = 1; int ans = 0; CLR(a, INF); REP(i, n) { int x = lower_bound(a, a + ans, ipt[i]) - a; dp[i] = x + 1; ans = max(ans, dp[i]); a[x] = ipt[i]; } cout << ans << endl; } return 0; }
时间: 2024-10-24 19:06:04