Cod sursa(job #1118892)

Utilizator visanrVisan Radu visanr Data 24 februarie 2014 13:44:03
Problema Subsir crescator maximal Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

#define LeftSon (2 * Node)
#define RightSon (2 * Node + 1)

const int NMAX = 100010;

int N, V[NMAX], W[NMAX], AintMax[4 * NMAX], AintPos[4 * NMAX], Best[NMAX], From[NMAX], Max, PosMax;
pair<int, int> P[NMAX];

void Update(int Node, int Left, int Right, int Pos, int Val, int PosVal)
{
    if(Left == Right)
    {
        if(Val > AintMax[Node])
        {
            AintMax[Node] = Val;
            AintPos[Node] = PosVal;
        }
        return ;
    }
    int Mid = (Left + Right) / 2;
    if(Pos <= Mid) Update(LeftSon, Left, Mid, Pos, Val, PosVal);
    else Update(RightSon, Mid + 1, Right, Pos, Val, PosVal);

    if(AintMax[LeftSon] > AintMax[RightSon]) AintMax[Node] = AintMax[LeftSon], AintPos[Node] = AintPos[LeftSon];
    else AintMax[Node] = AintMax[RightSon], AintPos[Node] = AintPos[RightSon];
}

void Query(int Node, int Left, int Right, int LeftBound, int RightBound)
{
    if(LeftBound > RightBound) return ;
    if(LeftBound <= Left && Right <= RightBound)
    {
        if(AintMax[Node] > Max) Max = AintMax[Node], PosMax = AintPos[Node];
        return ;
    }
    int Mid = (Left + Right) / 2;
    if(LeftBound <= Mid) Query(LeftSon, Left, Mid, LeftBound, RightBound);
    if(Mid < RightBound) Query(RightSon, Mid + 1, Right, LeftBound, RightBound);
}

int main()
{
    freopen("scmax.in", "r", stdin);
    freopen("scmax.out", "w", stdout);

    scanf("%i", &N);
    for(int i = 1; i <= N; ++ i)
    {
        scanf("%i", &V[i]);
        P[i] = make_pair(V[i], i);
    }

    int K = 0;
    sort(P + 1, P + N + 1);
    for(int i = 1; i <= N; ++ i)
    {
        if(P[i].first != P[i - 1].first) K ++;
        W[ P[i].second ] = K;
    }

    for(int i = 1; i <= N; ++ i)
    {
        Max = PosMax = 0;
        Query(1, 1, K, 1, W[i] - 1);
        Best[i] = Max + 1;
        From[i] = PosMax;
        Update(1, 1, K, W[i], Best[i], i);
    }

    Max = PosMax = 0;
    for(int i = 1; i <= N; ++ i)
        if(Best[i] > Max)
            Max = Best[i], PosMax = i;

    printf("%i\n", Max);
    vector<int> Sol;
    for(int i = PosMax; Best[i] > 0; i = From[i])
        Sol.push_back(V[i]);

    for(int i = Sol.size() - 1; i >= 0; -- i) printf("%i ", Sol[i]);
}