Cod sursa(job #4109)

Utilizator raula_sanChis Raoul raula_san Data 30 decembrie 2006 14:13:47
Problema Secv Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.32 kb
#include<cstdio>
#define dim 5001

int N, M, L[dim], S[dim], SOL = 5001; long A[dim], B[dim];

void read()
{
     freopen("secv.in", "r", stdin);
     scanf("%d", &N);
     
     int i;
     for(i=1; i<=N; ++i)
              scanf("%ld", A + i);
}

void swap(int i, int j)
{    B[i] ^= B[j] ^= B[i] ^= B[j];
     }

void heapUP(int k)
{
     if(k <= 1)
          return;
     int t = k / 2;
     if(B[t] < B[k])
     {
             swap(t, k);
             heapUP(t);
             }
}

void buildH()
{
     int i;
     for(i=2; i<=N; ++i)
              heapUP(i);
}

void restoreH(int r, int b)
{
     long st, dr, max;
     if(r << 1 <= b)
     {
          st = B[r<<1];
          
          if((r << 1) + 1 <= b)
                dr = B[(r<<1)+1];
          else
              dr = st - 1;
          
          max = st > dr ? r << 1 : (r << 1) + 1;
          
          if(B[r] < B[max])
          {
                  swap(max, r);
                  restoreH(max, b);
                  }
          }
}

void heapsort()
{
     int i;
	 for(i=N; i>1;)
     {
              swap(1, i);
              restoreH(1, --i);
              }
}

void copy()
{
     int i;
     for(i=1; i<=N; ++i)
              B[i] = A[i];
}

void dynamics()
{
     int i, j, p, max, maxs; L[1] = 1, S[1] = 1;
     for(i=2; i<=N; ++i)
     {        
              p = max = maxs = 0;
              for(j=1; j<i; ++j)
					   if(A[j] < A[i] && L[j] > max)
                               p = j, max = L[j], maxs = S[j];
                       else if(A[j] < A[i] && L[j] == max && S[j] > maxs)
                            p = j, maxs = S[j];
                       L[i] = max + 1; S[i] = maxs != 0 ? maxs : i;
                       if(L[i] == M && (i - S[i] + 1) < SOL)
                               SOL = (i - S[i] + 1);
              }
}

void c_array()
{
     long x = B[1], i; M = 1;
     for(i=2; i<=N; ++i)
              if(B[i] != x)
              {
                      B[++M] = B[i];
                      x = B[i];
                      }
}

int main()
{
    read(); copy();
    buildH(); heapsort();
    c_array(); dynamics();
    
    freopen("secv.out", "w", stdout);
    printf("%d", SOL != 5001 ? SOL : -1);
    
    fclose(stdin); fclose(stdout);
    return 0;
}