比赛 20120705 评测结果 AAAATAATAA
题目名称 数字计算 最终得分 80
用户昵称 Citron酱 运行时间 0.000 s
代码语言 C++ 内存使用 0.00 MiB
提交时间 2012-07-05 09:37:35
显示代码纯文本
#include <cstdio>

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

const short MAXn=20+1;
const short MAXt=200+1;

struct que
{
	short ls, lm;
	unsigned long long ss, sm;
	short d;
	que *next;
};

char s[MAXn];
short t, n, ans;
unsigned long long num[MAXn][MAXn];

inline void Input();
void Prework();
void Bfs();
inline void Output();

int main()
{
	freopen(I_F,"r",stdin);
	freopen(O_F,"w",stdout);
	Input();
	while (t>=0)
	{
		Prework();
		if (num[0][n]>t)
			Bfs();
		else if (num[0][n]==t)
			ans=0;
		Output();
		Input();
	}
	return 0;
}

inline void Input()
{
	scanf("%s\n%hd\n",s,&t);
}

void Prework()
{
	for (short i=0; i<MAXn; ++i)
		for (short j=0; j<MAXn; ++j)
			num[i][j]=0;
	for (n=0; s[n]!=0; n++);
	for (short i=0; i<n; ++i)
	{
		num[i][1]=s[i]-'0';
		for (short j=2; j<=n-i; ++j)
			num[i][j]=num[i][j-1]*10+s[i+j-1]-'0';
	}
}

void Bfs()
{
	ans=-1;
	unsigned long long tem;
	que *head, *tail, *temp;
	head=new que;
	head->ls=head->lm=head->d=0;
	head->ss=0;
	head->sm=1;
	head->next=NULL;
	tail=head;
	
	while (head!=NULL && ans==-1)
	{
		for (short i=head->lm+1; i<n && ans==-1; ++i)
		{
			tail->next=new que;
			tail=tail->next;
			tail->ls=head->ls;
			tail->lm=i;
			tail->ss=head->ss;
			tail->sm=head->sm*num[head->lm][i-head->lm];
			tail->d=head->d+1;
			tail->next=NULL;
			if (tail->ss+tail->sm*num[tail->lm][n-tail->lm]==t)
				ans=tail->d;
		}
		for (short i=head->lm+1; i<n && ans==-1; ++i)
		{
			tem=head->ss+head->sm*num[head->lm][i-head->lm];
			if (tem<=t)
			{
				tail->next=new que;
				tail=tail->next;
				tail->ls=tail->lm=i;
				tail->ss=tem;
				tail->sm=1;
				tail->d=head->d+1;
				tail->next=NULL;
				if (tem+num[tail->ls][n-tail->ls]==t)
					ans=tail->d;
			}
			else
				break;
		}
		temp=head;
		head=head->next;
		delete temp;
	}
	
	while (head!=NULL)
	{
		temp=head;
		head=head->next;
		delete temp;
	}
}

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