比赛 20120613 评测结果 WWWWWWWWWA
题目名称 表达式 最终得分 10
用户昵称 Citron酱 运行时间 0.000 s
代码语言 C++ 内存使用 0.00 MiB
提交时间 2012-06-13 16:56:40
显示代码纯文本
#include <cstdio>
#include <climits>

#define I_F "expressb.in"
#define O_F "expressb.out"

struct que
{
	short s,a,b;
	que *next;
};

long n,k;
int ans;

void Input();
inline int Max(const int&, const int&);
inline int Min(const int&, const int&);
void Exchange(const long, short&, short&, short&);
void Search();
void Output();

int main()
{
	freopen(I_F,"r",stdin);
	freopen(O_F,"w",stdout);
	short t;
	for (scanf("%hd",&t); t>0; --t)
	{
		Input();
		Search();
		Output();
	}
	return 0;
}

void Input()
{
	scanf("%ld%ld",&n,&k);
}

inline int Max(const int &a, const int &b)
{
	return (a>b)?a:b;
}

inline int Min(const int &a, const int &b)
{
	return (a<b)?a:b;
}

void Exchange(const long x, short &s, short &a, short &b)
{
	s=0;
	a=-1;
	b=SHRT_MAX;
	for (long y=x; y>0; y/=10)
	{
		s+=y%10;
		a=Max(a,y%10);
		b=Min(b,y%10);
	}
	if (a==-1)
		a=b;
}

void Search()
{
	ans=0;
	if (n==k)
		return;
	ans=INT_MAX;
	
	int t;
	short s,a,b;
	int d[83][10][10];
	bool f[83][10][10]={false};
	for (short i=0; i<83; ++i)
		for (short j=0; j<10; ++j)
			for (short k=0; k<10; ++k)
				d[i][j][k]=-1,
	Exchange(n,s,a,b);
	d[s][a][b]=0;
	f[s][a][b]=true;
	
	que *q=new que, *qt;
	q->s=s;
	q->a=a;
	q->b=b;
	q->next=NULL;
	qt=q;
	
	que *head=new que, *tail, *temp;
	head->s=s;
	head->a=a;
	head->b=b;
	head->next=NULL;
	tail=head;
	
	while (head!=NULL)
	{
		for (que *i=q; i!=NULL; i=i->next)
		{
			t=head->s*i->a+i->b;
			Exchange(t,s,a,b);
			if (d[s][a][b]==-1)
			{
				d[s][a][b]=d[head->s][head->a][head->b]+d[i->s][i->a][i->b]+1;
				qt->next=new que;
				qt=qt->next;
				qt->s=s;
				qt->a=a;
				qt->b=b;
				qt->next=NULL;
				tail->next=new que;
				tail=tail->next;
				tail->s=s;
				tail->a=a;
				tail->b=b;
				tail->next=NULL;
				f[s][a][b]=true;
			}
			else if (d[head->s][head->a][head->b]+d[i->s][i->a][i->b]+1<d[s][a][b])
			{
				d[s][a][b]=d[head->s][head->a][head->b]+d[i->s][i->a][i->b]+1;
				if (!f[s][a][b])
				{
					tail->next=new que;
					tail=tail->next;
					tail->s=s;
					tail->a=a;
					tail->b=b;
					tail->next=NULL;
					f[s][a][b]=true;
				}
			}
			
			if (t==k)
				ans=Min(ans,d[head->s][head->a][head->b]+d[i->s][i->a][i->b]+1);
		}
		temp=head;
		head=head->next;
		f[temp->s][temp->a][temp->b]=true;
		delete temp;
	}
	
	if (ans==INT_MAX)
		ans=-1;
}

void Output()
{
	printf("%d\n",ans);
}