Cod sursa(job #538781)

Utilizator crushackPopescu Silviu crushack Data 21 februarie 2011 21:51:55
Problema Elimin 2 Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.73 kb
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define LMax 2010
using namespace std;

const char IN[]="elimin2.in",OUT[]="elimin2.out";

int N;
char s[LMax], rez[LMax];
int t[LMax][LMax];
int a[10][LMax];

void solve(int x,int y)
{
	int i,max=-1,*low,*upp;
	if (y-x<=0) t[x][y]=1;
	if (y-x==1)
	{
		if (s[x]==s[y]) t[x][y]=2;
		else t[x][y]=1;
		return;
	}
	if (t[x][y]>0) return;
	
	for (i=9;i>=0;--i)
	{
		low=lower_bound( a[i]+1 , a[i]+a[i][0]+1 , x );
		upp=upper_bound( a[i]+1 , a[i]+a[i][0]+1 , y )-1;
		if ( (int)(*upp-*low)<=1 ) continue;
		
		max= t[*low+1][*upp-1]>max ? t[*low+1][*upp-1] : max;
	}
	t[x][y]= max!=-1 ? max+2 : 1;
}

void solve()
{
	int i,j;
	for (j=0;j<=N;++j)
		for (i=0;i+j<N;++i)
			solve(i,i+j);
}

void init()
{
	int i,j;
	N=strlen(s);
	for (i=0;i<=9;++i)
		for (j=0;j<N;++j) if (s[j]==i+'0')
			a[i][++a[i][0]]=j;
}

void make_sol(int x=0,int y=N-1,int c=0)
{
	int i,*upp,*low,max=-1,nx=-1,ny=-1;
	if (t[x][y]==1)
	{
		for (i=x;i<=y;++i)
			if ( s[i]-'0'>max)
				max=s[i]-'0';
		rez[c]=max+'0';
		return;
	}
	if (y-x==1)
	{
		rez[c]=s[x];
		rez[c+1]=s[y];
		return;
	}
	for (i=9;i>=0;--i)
	{
		low=lower_bound( a[i]+1 , a[i]+a[i][0]+1 , x );
		upp=upper_bound( a[i]+1 , a[i]+a[i][0]+1 , y )-1;
		if ( (int)(*upp-*low)<=1 || *low<x || *upp>y ) continue;
		if (t[*low+1][*upp-1]>max)
		{
			max=t[*low+1][*upp-1];
			nx=*low+1;
			ny=*upp-1;
		}
	}
	rez[c]=s[nx-1];
	rez[c+t[x][y]-1]=s[ny+1];
	
	if (nx<=ny)
		make_sol(nx,ny,c+1);
}

int main()
{
	freopen(IN,"r",stdin);
	scanf("%s",s);
	fclose(stdin);
	
	init();
	solve();
	make_sol();
	
	freopen(OUT,"w",stdout);
	printf("%s\n",rez);
	fclose(stdout);
	
	return 0;
}