您的位置:首页 > 大数据 > 人工智能

HDU 1104 Remainder

2016-01-15 08:53 447 查看
BFS。

#include<cstdio>
#include<cstring>
#include<queue>
#include<string>
#include<algorithm>
#include<map>
#include<iostream>
using namespace std;

int n,m,k;
struct Node
{
int nowN;
int tot;
string op;
Node(int t,int nown,string o)
{
tot=t;
nowN=nown;
op=o;
}
};
queue<Node>Q;
map<int,int>t;

int MOD(int a,int b)
{
if(a>=0) return a%b;
if(abs(a)%b==0) return 0;
return (a+b*(abs(a)/b+1));
}

void BFS()
{
int flag=0;
while(!Q.empty()) Q.pop();
t.clear();
Node s(0,MOD(n,m*k),"");
Q.push(s);
while(!Q.empty())
{
Node head=Q.front(); Q.pop();

if(MOD(n+1,k)==MOD(head.nowN,k))
{
flag=1;
printf("%d\n",head.tot);
cout<<head.op<<endl;
break;
}
if(t[MOD(head.nowN+m,m*k)]==0)
{
t[MOD(head.nowN+m,m*k)]=1;
Node s1(head.tot+1,MOD(head.nowN+m,m*k),head.op+"+");
Q.push(s1);
}
if(t[MOD(head.nowN-m,m*k)]==0)
{
t[MOD(head.nowN-m,m*k)]=1;
Node s2(head.tot+1,MOD(head.nowN-m,m*k),head.op+"-");
Q.push(s2);
}
if(t[MOD(head.nowN*m,m*k)]==0)
{
t[MOD(head.nowN*m,m*k)]=1;
Node s3(head.tot+1,MOD(head.nowN*m,m*k),head.op+"*");
Q.push(s3);
}
if(t[MOD(MOD(head.nowN,m),m*k)]==0)
{
t[MOD(MOD(head.nowN,m),m*k)]=1;
Node s4(head.tot+1,MOD(MOD(head.nowN,m),m*k),head.op+"%");
Q.push(s4);
}
}
if(!flag) printf("0\n");
}

int main()
{
while(~scanf("%d%d%d",&n,&k,&m))
{
if(!n&&!m&&!k) break;
BFS();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: