HDU 1104 Remainder
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; }