定义两个字符串变量:s
和m
,再定义两种操作,
第一种操作:
m = s
; s = s + s
;
第二种操作:
s = s + m
;
假设s
, m
初始化如下:
s = "a"
; m = s
;
求最小的操作步骤数,可以将s
拼接到长度等于n
class Nodes{
int s;
int m;
public Nodes(){
}
public Nodes(int s,int m){
this.s=s;
this.m=m;
}
}
public class BFS {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
Nodes nodes=new Nodes(1,1);
Map<Nodes,Integer> map=new HashMap<Nodes,Integer>();
map.put(nodes,0);
Queue<Nodes> queue=new LinkedList();
queue.add(nodes);
while (!queue.isEmpty()){
Nodes nodes1=queue.poll();
if (nodes1.s==n){
System.out.println(map.get(nodes1));
break;
}
Nodes left=new Nodes();
left.m=nodes1.s;
left.s=nodes1.s*2;
map.put(left,map.get(nodes1)+1);
queue.add(left);
Nodes right=new Nodes();
right.s=nodes1.s+nodes1.m;
right.m=nodes1.m;
map.put(right,map.get(nodes1)+1);
queue.add(right);
}
}
}