题目描述:
要求选给出思路,然后写代码,可以使用c/c++/java/python或者伪代码描述。
有两个数,A和B,六种操作分别是+12,-12,+7,-7,+5,-5。A经过若干次操作,变成B
是输入任意2个数A和B,要给出变换过程,这其中的操作序列就是一个路径,也就是最少的操作次数 。
网上没有搜到答案,自己实现了一下,初步测试正确,不知道是否有BUG,发现BUG的请留言。
import java.util.Scanner;
public class Sogou {
static Scanner sc = new Scanner(System.in);
public static int a = sc.nextInt();
public static int b = sc.nextInt();
public static String result = "";
public static void main(String[] args) {
sc.close();
excute(a, b);
}
static void excute(int a, int b) {
int m,n;
if(a <= b){
m = (b - a) / 12;
n = (b - a) % 12;
sprint(m, n);
System.out.println(Sogou.a + Sogou.result + Sogou.b);
}
else{
m = (a - b) / 12;
n = (a - b) % 12;
sprint(m, n);
System.out.println(Sogou.a + Sogou.result.replaceAll("\\+", "*").replaceAll("-", "+").replaceAll("\\*", "-") + Sogou.b);
}
}
static void sprint(int m, int n) {
String sum = "";
for (int i = 0; i < m; i++) {
sum += " +12";
}
switch(n){
case 0:
Sogou.result = sum + " ";
break;
case 5:
Sogou.result = sum + " +5 ";
break;
case 7:
Sogou.result = sum + " +7 ";
break;
case 10:
Sogou.result = sum + " +5 +5 ";
default:
break;
}
if(m == 0){
switch (n) {
case 1:
Sogou.result = " +5 +5 +5 -7 -7 ";
break;
case 2:
Sogou.result = " +7 -5 ";
break;
case 3:
Sogou.result = " +5 +5 -7 ";
break;
case 4:
Sogou.result = " +7 +7 -5 -5 ";
break;
case 6:
Sogou.result = " +7 +7 +7 -5 -5 -5 ";
break;
case 8:
Sogou.result = " +5 +5 +5 -7 ";
break;
case 9:
Sogou.result = " +7 +7 -5 ";
break;
case 11:
Sogou.result = " +7 +7 +7 -5 -5 ";
break;
default:
break;
}
}
else {
switch (n) {
case 1:
switch (m) {
case 1:
Sogou.result = " +5 +5 +5 +5 -7 ";
break;
default:
sum = "";
for(int i=0; i<m-2; i++){
sum += " +12";
}
Sogou.result = sum + " +5 +5 +5 +5 +5 ";
break;
}
break;
case 2:
sum = "";
for(int i=0; i<m-1; i++){
sum += " +12";
}
Sogou.result = sum + " +7 +7 ";
break;
case 3:
sum = "";
for(int i=0; i<m-1; i++){
sum += " +12";
}
Sogou.result = sum +" +5 +5 +5 ";
break;
case 4:
switch (m) {
case 1:
Sogou.result = " +7 +7 +7 -5 ";
break;
default:
sum = "";
for(int i=0; i<m-2; i++){
sum += " +12";
}
Sogou.result = sum + " +7 +7 +7 +7 ";
break;
}
break;
case 6:
switch (m) {
case 1:
Sogou.result = " +7 +7 +7 +7 -5 -5 ";
break;
case 2:
sum = "";
for(int i=0; i<m-2; i++){
sum += " +12";
}
Sogou.result = sum + " +7 +7 +7 +7 +7 -5 ";
break;
default:
sum = "";
for(int i=0; i<m-3; i++){
sum += " +12";
}
Sogou.result = sum + " +7 +7 +7 +7 +7 +7 ";
break;
}
break;
case 8:
sum = "";
for(int i=0; i<m-1; i++){
sum += " +12";
}
Sogou.result = sum + " +5 +5 +5 +5 ";
break;
case 9:
sum = "";
for(int i=0; i<m-1; i++){
sum += " +12";
}
Sogou.result = sum + " +7 +7 +7 ";
break;
case 11:
switch (m) {
case 1:
Sogou.result = " +7 +7 +7 +7 -5 ";
break;
default:
sum = "";
for(int i=0; i<m-2; i++){
sum += " +12";
}
Sogou.result = sum + " +7 +7 +7 +7 +7 ";
break;
}
break;
default:
break;
}
}
}
}