POJ 3903 Stock Exchange(LIS || 线段树)题解
题意:求最大上升子序列
思路:才发现自己不会LIS,用线段树写的,也没说数据范围就写了个离散化,每次查找以1~a[i]-1结尾的最大序列答案,然后更新,这样遍历一遍就行了。最近代码总是写残啊...
刚看了LIS的nlogn写法(贪心+二分):维护一个dp[i]表示最大长度为i时的最小结尾,初始memset为INF,最终dp数组的长度为答案。这个很好维护,如果当前的a[i]比dp[len]要大,那么显然最大长度加一,dp[len + 1] = a[i];如果比dp[len]小,那么我就去二分查找前面的第一个dp[x]大于等于a[i],替换掉,因为长度x的结尾越小越好。
LIS代码:
#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; int a[maxn], dp[maxn]; int main(){ int n; while(~scanf("%d", &n)){ memset(dp, INF, sizeof(dp)); for(int i = 1; i <= n; i++) scanf("%d", &a[i]); dp[1] = a[1]; int len = 1; for(int i = 2; i <= n; i++){ if(a[i] > dp[len]){ dp[++len] = a[i]; } else{ int pos = lower_bound(dp + 1, dp + len + 1, a[i]) - dp; if(pos != len + 1){ dp[pos] = a[i]; } } } printf("%d\n", len); } return 0; }
线段树代码:
#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 */