1. 程式人生 > >POJ 3903 Stock Exchange(LIS || 線段樹)題解

POJ 3903 Stock Exchange(LIS || 線段樹)題解

題意:求最大上升子序列

思路:才發現自己不會LIS,用線段樹寫的,也沒說資料範圍就寫了個離散化,每次查詢以1~a[i]-1結尾的最大序列答案,然後更新,這樣遍歷一遍就行了。最近程式碼總是寫殘啊...

程式碼:

#include<set>
#include<map>
#include<stack>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include
<iostream> #include<algorithm> typedef long long ll; using namespace std; const int maxn = 1e5 + 10; const int seed = 131; const ll MOD = 100000007; const int INF = 0x3f3f3f3f; ll a[maxn], b[maxn]; ll Max[maxn << 2]; void update(int l, int r, int pos, ll v, int rt){ if(l == r){ Max[rt]
= max(Max[rt], v); return; } int m = (l + r) >> 1; if(pos <= m) update(l, m, pos, v, rt << 1); else update(m + 1, r, pos, v, rt << 1 | 1); Max[rt] = max(Max[rt << 1], Max[rt << 1 | 1]); } int query(int l, int r, int
L, int R, int rt){ if(R < 1) return 0; if(L <= l && R >= r){ return Max[rt]; } int m = (l + r) >> 1, ans = 0; if(L <= m) ans = max(ans, query(l, m, L, R, rt << 1)); if(R > m) ans = max(ans, query(m + 1, r, L, R, rt << 1 | 1)); return ans; } int main(){ int n; while(~scanf("%d", &n)){ memset(Max, 0, sizeof(Max)); for(int i = 1; i <= n; i++) scanf("%lld", &a[i]), b[i] = a[i]; sort(b + 1, b + n + 1); for(int i = 1; i <= n; i++) a[i] = lower_bound(b + 1, b + n + 1, a[i]) - b; int ans = 0; for(int i = 1; i <= n; i++){ int temp = query(1, n, 1, a[i] - 1, 1) + 1; ans = max(ans, temp); update(1, n, a[i], temp, 1); } printf("%d\n", ans); } return 0; } /* 10 1 5 2 7 5 9 10 465 10 78 */