Cod sursa(job #1273578)

Utilizator yololy97Olaru Bogdan-Ioan yololy97 Data 22 noiembrie 2014 19:03:54
Problema Subsir crescator maximal Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include <cstdio>
#include <algorithm>
#include <vector>
#define N 100001
using namespace std;
int dp[N], v[N],init[N], t[N], n, H[3 * N], maxim;
struct nod{
    int val, ind;
}a[N];
struct cmp{
    bool operator()(const nod &a, const nod &b) const{
        if(a.val < b.val)
            return true;
        return false;
    }
};
void update(int node, int L, int R, int pos, int val){
    int M = (L + R) / 2;
    if(L == R)
        H[node] = val;
    else{
        if(pos <= M)
            update(node * 2, L, M, pos, val);
        else
            update(node * 2 + 1, M + 1, R, pos, val);
        if (dp[ H[2 * node] ] > dp[ H[2 * node + 1] ] )
            H[node] = H[2 * node];
        else
            H[node] = H[2 * node + 1];
    }
}
int query(int node, int L, int R, int ql, int qr){
    if(ql <= L && qr >= R)
        return H[node];
    int M = (L + R) / 2, maxi = 0;
    if(ql <= M)
        maxi = query(node * 2, L, M, ql, qr);
    if(qr > M) {
        int p = query(node * 2 + 1, M + 1, R, ql, qr);
        if (dp[p] > dp[maxi])
            maxi = p;
    }
    return maxi;
}
int main(){
    freopen("scmax.out", "w", stdout);
    freopen("scmax.in", "r", stdin);
    scanf("%d ",&n);
    for(int i = 1; i <= n; ++i)
        scanf("%d ", &a[i].val),
        a[i].ind = i;
    sort(a + 1, a + n + 1, cmp());
    int j = 0, end_pos = 0;
    for(int i = 1; i <= n; ++i)
        if(a[i].val != a[i - 1].val)
            v[a[i].ind] = ++j,
            init[a[i].ind] = a[i].val;
        else
            v[a[i].ind] = j,
            init[a[i].ind] = a[i].val;
    for(int i = 1; i <= n; ++i){
        int poz = 0;
        if(v[i] > 1)
            poz = query(1, 1, n, 1, v[i] - 1);

        dp[i] = 1 + dp[poz];
        t[i] = poz;
        update(1, 1, n, v[i], i);
        if(dp[i] > maxim) {
            maxim = dp[i];
            end_pos = i;
        }
    }

    printf("%d\n", maxim);
    vector<int> sol;
    for (int i = end_pos; i; i = t[i])
        sol.push_back(init[i]);
    for (int i = sol.size() - 1; i >= 0; --i)
        printf ("%d ", sol[i]);
    printf ("\n");
}