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
*/

猜你喜欢

转载自www.cnblogs.com/KirinSB/p/10063783.html