现在的位置: 首页 > 综合 > 正文

hdu1104 Remainder bfs找算式是否有解……

2019年11月07日 ⁄ 综合 ⁄ 共 905字 ⁄ 字号 评论关闭

需要注意的是,进行模运算剪枝……

#include<iostream>
#include<queue>
#include<cstdlib>
#include<cstring>
using namespace std;
int N,M,K,T,X;
bool used[1010];
struct node
{
	int value,step;
	char prc[10000];
}st;
int remind(int a,int b)
{
	return (a%b+b)%b;
}
void init()
{
	T=remind(N+1,K);
	st.value=N;
	X=M*K;
	st.step=0;
	memset(used,0,sizeof(used));
	used[st.value]=1;
}
void bfs()
{
	int i,tmp,tmp1;
	queue<node>qq;
	node t1,t2;
	qq.push(st);
	while(qq.size())
	{
		t1=qq.front();
		qq.pop();
		if(remind(t1.value,K)==T)
		{
			t1.prc[t1.step]='\0';
			printf("%d\n%s\n",t1.step,t1.prc);
			return;
		}
		for(i=0;i<4;i++)
		{
			t2=t1;
			t2.step++;
			if(i==0)
			{
				tmp=(t2.value+M)%X;
				t2.prc[t1.step]='+';
			}
			else if(i==1)
			{
				tmp=(t2.value-M)%X;
				t2.prc[t1.step]='-';
			}
			else if(i==2)
			{
				tmp=(t2.value*M)%X;
				t2.prc[t1.step]='*';
			}
			else
			{
				tmp=remind(t2.value,M);
				t2.prc[t1.step]='%';
			}
			tmp1=remind(tmp,K);
			if(!used[tmp1])
			{
				used[tmp1]=1;
				t2.value=tmp;
				qq.push(t2);
			}
		}
	}
	printf("0\n");
}
int main()
{
	while(scanf("%d%d%d",&N,&K,&M)&&(N!=0||M!=0||K!=0))
	{
		init();
		bfs();
	}
}

抱歉!评论已关闭.