Cod sursa(job #1246566)

Utilizator vlad.doruIon Vlad-Doru vlad.doru Data 21 octombrie 2014 12:13:07
Problema Subsir crescator maximal Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream in("scmax.in");
ofstream out("scmax.out");

int main (int argc, char const *argv[]) {
  int n;
  in>>n;
  vector<int> v;
  vector<int> dp = {0};
  vector<int> prev = {-1};
  int max_length = 0;

  for(int i = 0; i < n; ++i) {
    int x;
    in>>x;
    v.push_back(x);
    // We do binary search here
    int step = 1;
    for(;step <= max_length; step<<=1);
    int pos = 0;
    for(; step; step>>=1) {
      if (pos + step <= max_length && v[dp[pos + step]] < x) {
        pos+= step;
      }
    }
    if (pos == max_length) {
      dp[++max_length] = i;
    } else {
      dp[pos + 1] = i;
    }
    prev.push_back(dp[pos]);
  }

  out<<max_length<<"\n";
  int pos = max_length;
  stack<int> result;
  while(pos >= 0) {
    result.push(v[pos + 1]);
    pos = prev[pos];
  }
  while(!result.empty()) {
    out<<result.top()<<" ";
    result.pop();
  }


  return 0;
}