Cod sursa(job #1645312)

Utilizator serbanSlincu Serban serban Data 10 martie 2016 11:55:11
Problema Subsir crescator maximal Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <stack>
#define zero(x) ((x ^ (x - 1)) & x)

using namespace std;

stack<int> s;
int t[100005];
int a[100005], n;
pair<int, int> h[100005];

void update(int poz, int val) {
    for(int i = poz; i <= n; i += zero(i))
        if(h[i].first < val) {
            h[i].first = val;
            h[i].second = a[poz];
        }
        else if(h[i].first == val) h[i].second = min(h[i].second, a[poz]);
}

int caut(int poz) {
    int mx = 0, ret;
    for(int i = poz; i; i -= zero(i)) {
        if(h[i].second < a[poz] && mx < h[i].first)
            mx = h[i].first, ret = i;
    }
    return ret;
}

int main()
{
    ifstream f("scmax.in");
    ofstream g("scmax.out");
    int maxim = 0, poz; f >> n;
    for(int i = 1; i <= n; i ++) f >> a[i];
    for(int i = 1; i <= n; i ++) {
        int aux = caut(i);
        int mx = h[aux].first + 1;
        t[i] = aux;
        update(i, mx);
        if(mx > maxim) {
            maxim = mx;
            poz = i;
        }
    }
    g << maxim << "\n";
    while(poz != 0) {
        s.push(poz);
        poz = t[poz];
    }
    while(!s.empty()) g << a[s.top()] << " ", s.pop();
    g << "\n";
    return 0;
}