题意理解
这个题目就是说,要你把原来的字符串A经过若干次变换之后,变成字符串B。一开始我写的是一个深搜,丝毫没有考虑到标签的感受,但是经过了提交的若干发RE(实际是TLE)之后,我意识到好像是不可以的,就比如说,如果有替换规则
#define a aa
这样子,就很容易爆炸,搜不出结果。并且考虑到最快,所以还是用广搜。
代码
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
class Node {
String string;
int n;
public Node(String string, int n) {
this.string = string;
this.n = n;
}
}
public class Main {
static Queue<Node> ss = new ArrayDeque<>();
static Set<String> existed = new HashSet<>();
static String[] A = new String[11];
static String[] B = new String[11];
static int cnt = 0;
static int min = 20;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
A[cnt] = scanner.next();
B[cnt] = scanner.next();
cnt++;
}
scanner.close();
Node n1 = new Node(A[0], 0);
ss.add(n1);
existed.add(A[0]);
while (!ss.isEmpty()) {
Node head = ss.poll();
if (head.n > 10) {
break;
}
if (head.string.equals(B[0])) {
min = head.n;
break;
}
for (int i = 1; i < cnt; i++) {
int hLen = head.string.length();
int aLen = A[i].length();
for (int j = 0; j <= hLen - aLen; j++) {
if (head.string.substring(j, j + aLen).equals(A[i])) {
String next = head.string.substring(0, j) + B[i] + head.string.substring(j + aLen);
if (existed.contains(next)) {
continue;
} else {
existed.add(next);
int n = head.n + 1;
Node newNode = new Node(next, n);
ss.add(newNode);
}
}
}
}
}
if (min > 10) {
System.out.println("NO ANSWER!");
} else {
System.out.println(min);
}
}
}