首先养成解题思路 :
题目要求最小路径,,那肯定是BFS,又有顺序要求,那么只要保证正确的步骤 即 + - * %最先得到的答案肯定是满足题目的。
所以这道题大基调就是BFS,至于路径长度和路径有一个结构体进行记录。
本文 是mod 运算。。 mod 和% 的区别是%是有负有正, mod根据题目定义 a=b*q+r; a%q=r; 0<=r
#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define MAX 3005
struct Node{
int n;
string step;
};
bool visited[MAX];
int n,k,m;
char op[]={'+','-','*','%'};
Node bfs(){
int r=(((n+1)%k)+k)%k;
int km=k*m;
queue<Node> q;
Node tmp;
tmp.n=n;
tmp.step="";
q.push(tmp);
visited[((tmp.n%k)+k)%k]=true;
while(!q.empty()){
Node t=q.front();
q.pop();
if((((t.n%k)+k)%k)==r){
return t;
}
Node temp;
int next;
string step;
for(int i=0;i<4;i++){
if(op[i]=='+'){
next=(t.n+m)%km; //important
step=t.step+"+";
}else if(op[i]=='-'){
next=(t.n-m)%km; //important
step=t.step+"-";
}else if(op[i]=='*'){
next=(t.n*m)%km;//important
step=t.step+"*";
}else if(op[i]=='%'){
next=(t.n%m+m)%m%km; //important
step=t.step+"%";
}
if(visited[((next%k)+k)%k])continue;
visited[((next%k)+k)%k]=true;
temp.n=next;
temp.step=step;
q.push(temp);
}
}
return tmp;
}
int main()
{
while(cin>>n>>k>>m){
if(n==0&&k==0&&m==0) break;
memset(visited,false,sizeof(visited));
Node result;
result=bfs();
if(result.step=="")cout<<"0"<<endl;
else {
cout<<result.step.length()<<endl;
cout<<result.step<<endl;
}
}
return 0;
}

本文探讨如何使用BFS解决寻找最小路径的问题,重点在于理解模运算(mod)的特性,特别是与百分号(%)的区别。通过确保操作顺序正确,可以找到满足条件的最小路径。在解决问题的过程中,利用结构体记录路径长度和顺序。
247

被折叠的 条评论
为什么被折叠?



