Cod sursa(job #314061)

Utilizator mlazariLazari Mihai mlazari Data 10 mai 2009 14:54:35
Problema Subsir crescator maximal Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include<stdio.h>
#define NMAX 100002

int i,imax,n,lh,lr,a[NMAX],h[NMAX],v[NMAX],aib[NMAX],d[NMAX],p[NMAX],r[NMAX];

// begin - heap operations
void initheap() {
  for(int i=1;i<=n;i++) h[i]=i;
}

void swap(int &x,int &y) {
  int z=x;
  x=y;
  y=z;
}

void upheap(int x) {
  int p;
  while(x>1) {
    p=x>>1;
    if(a[h[x]]<a[h[p]]) {
      swap(h[x],h[p]);
      x=p;
    }
    else x=1;
  }
}

void downheap(int x) {
  int f,p;
  while(x<=lh>>1) {
    f=x;
    p=x<<1;
    if(a[h[p]]<a[h[f]]) f=p;
    if((p<lh)&&(a[h[p+1]]<a[h[f]])) f=p+1;
    if(a[h[x]]>a[h[f]]) {
      swap(h[x],h[f]);
      x=f;
    }
    else x=lh;
  }
}

int minheap() {
  swap(h[1],h[lh--]);
  downheap(1);
  return h[lh+1];
}

void doheap() {
  initheap();
  lh=0;
  while(lh<n) upheap(++lh);
}
// end - heap operations

void vcalculate() {
  int k=1,p=minheap(),c;
  v[0]=1;
  v[p]=k;
  for(int i=2;i<=n;i++) {
    c=minheap();
    if(a[p]==a[c]) v[c]=k; else v[c]=++k;
    p=c;
  }
}

// begin - AIB operations
void update(int x,int ind) {
  while(x<=n) {
    if(d[ind]>d[aib[x]]) aib[x]=ind;
    x+=x^(x-1)&x;
  }
}

int query(int x) {
  int max=0;
  while(x) {
    if(d[aib[x]]>d[max]) max=aib[x];
    x-=x^(x-1)&x;
  }
  return max;
}
// end - AIB operations

// begin - I/O operations
void readfile() {
  freopen("scmax.in","r",stdin);
  scanf("%d",&n);
  for(int i=1;i<=n;i++) scanf("%d",a+i);
  fclose(stdin);
}

void writefile() {
  freopen("scmax.out","w",stdout);
  printf("%d\n",lr);
  for(int i=1;i<=lr;i++) printf("%d ",r[i]);
  fclose(stdout);
}
// end - I/O operations

int main() {
  readfile();
  doheap();
  vcalculate();
  d[0]=0;
  for(i=1;i<=n;i++) {
    p[i]=query(v[i]-1);
    d[i]=d[p[i]]+1;
    update(v[i],i);
  }
  imax=1;
  for(i=2;i<=n;i++)
   if(d[i]>d[imax]) imax=i;
  lr=d[imax];
  r[lr]=a[imax];
  for(i=lr-1;i>0;i--) {
    imax=p[imax];
    r[i]=a[imax];
  }
  writefile();
  return 0;
}