注解
1、广度优先遍历:加减乘和取余,四种运算。按照题目给定的优先级顺序依次计算。
2、visit数组(最大为K * M),记录已经出现过的数字,不需要重复遍历,避免超时。
3、每一步均需要取余(注意是统一对K * M取余,否则对M取余再对K取余,答案不一致。),否则数字太大,队列里的数字计算不完,也会超时。
4、注意取mod与%取余的区别。本题的余数不能为负数,应该是mod运算,而不是直接用%,那样得到的是有负数的余数。
代码
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct Node {
int num;
int step;
string road;
};
int visit[1000*1000+10];
int N, M, K;
string op[] = {"+", "-", "*", "%"};
void BFS(int init) {
memset(visit, 0, sizeof(visit));
queue<Node> q;
int isOut = 0;
Node node = {init, 0, ""};
q.push(node);
visit[(node.num%K+K)%K] = 1;
while(q.size()>0) {
Node top = q.front();
q.pop();
if( ((init+1)%K+K)%K == ((top.num)%K+K)%K ) {
cout<<top.step<<endl;
cout<<top.road<<endl;
isOut = 1;
break;
}
for(int i=0; i<4; i++) {
int ans;
if(i==0) {
ans = (top.num+M) % (K*M);
} else if(i==1) {
ans = (top.num-M) % (K*M);
} else if(i==2) {
ans = (top.num*M) % (K*M);
} else {
ans = (top.num%M+M) % M % (K*M);
}
Node tmp = {ans, top.step+1, top.road+op[i]};
if(!visit[(ans%K+K)%K]) {
q.push(tmp);
visit[(ans%K+K)%K] = 1;
}
}
}
if(!isOut) {
cout<<0<<endl;
}
}
int main() {
cin>>N>>K>>M;
while(N || K || M) {
BFS(N);
cin>>N>>K>>M;
}
return 0;
}