Cod sursa(job #842127)

Utilizator stoicatheoFlirk Navok stoicatheo Data 26 decembrie 2012 11:43:07
Problema Elimin 2 Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.89 kb
#include <stdio.h>
#define Nmax 2003
#define I short int
#define Cmax 10

I N[Nmax],nr[Nmax];
I l[Nmax][Nmax];
I left[Cmax][Nmax],right[Cmax][Nmax];
I i,j,n,xx,yy,c,st,dr,cif,lmax,lg,y;
char cc;
I max(I x,I y){ return x>y ? x : y; }

void prep_left_right(){
    I i,c;
   for(c=0;c<10;++c)
    for(i=1;i<=n;++i)
       left[c][i]=10000;
   for(c=0;c<10;++c){
    for(i=1;i<=n;++i)
        if(N[i] == c) right[c][i] = i;
         else right[c][i] = right[c][i-1];
      for(i=n;i>=1;--i)
        if(N[i] == c) left[c][i] = i;
         else left[c][i] = left[c][i+1];
   }
}

void solve(){
    I i,j,lg;
   for(i=1;i<=n;++i) l[i][i]=1;
   for(lg=2; lg<=n; ++lg)
    for(i=1; (j=i+lg-1)<=n; ++i){

         l[i][j] =  l[i+1][j]> l[i][j-1] ? l[i+1][j] : l[i][j-1];
         if(right[N[i]][j] >= i+1 )
           l[i][j] =  l[i][j]> l[i+1][right[N[i]][j]-1]+2 ? l[i][j] : l[i+1][right[N[i]][j]-1]+2;
         if(left[N[j]][i] <= j-1 )
           l[i][j] = l[i][j]> l[left[N[j]][i]+1][j-1]+2 ? l[i][j] : l[left[N[j]][i]+1][j-1]+2;
      }
}

void reconst(I i,I j,I x){
    I c;
    for(xx=2;xx<=lmax/2+(lmax &1);xx++)
      for(c=9; c>=0; --c)
        if( l[left[c][i]][right[c][j]] == x ){
            nr[xx]=c, nr[lmax-xx+1]=c;
            i=left[c][i]+1, j=right[c][j]-1;
            x-=2;
            break;
         }
}

int main(){
    freopen("elimin2.in","r",stdin);
   freopen("elimin2.out","w",stdout);
   for(scanf("%c",&cc); cc!='n' && !feof(stdin); scanf("%c",&cc))
    N[++n]=cc-'0';

   prep_left_right();

   solve();

   for(c=9; c>=1; --c)
    if( l[left[c][1]][right[c][n]] > lmax ){
          lmax=l[left[c][1]][right[c][n]];
          cif=c;
      }
   nr[xx=1]=cif; nr[lmax-xx+1]=cif;
   reconst(left[cif][1]+1,right[cif][n]-1,lmax-2);

   for(i=1;i<=lmax;++i) printf("%d",nr[i]);
   printf("\n");
   fclose(stdin); fclose(stdout);
   return 0;
}