题解 | 时津风的资源收集
时津风的资源收集
https://www.nowcoder.com/practice/5a6f83a0e0214ba5a77f6cdc71a3027b
import java.io.*;
import java.util.*;
public class Main {
// 定义一个静态数组dist,用于存储从数字10到其他数字的最小步数
private static int[] dist = new int[301];
public static void main(String[] args)throws IOException{
// 调用bfs方法计算最小步数
bfs();
// 初始化输入输出流
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// 读取测试用例数量
int T = Integer.parseInt(br.readLine().trim());
// 处理每个测试用例
while (T-- >0){
// 读取一行输入并分割成字符串数组
String[] str = br.readLine().trim().split("\\s+");
// 将字符串数组转换为四个整数
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
int c = Integer.parseInt(str[2]);
int d = Integer.parseInt(str[3]);
// 计算四个数字的最小步数之和
int ans = dist[a]+dist[b]+dist[c]+dist[d];
// 输出结果
out.println(ans);
}
// 刷新并关闭输出流
out.flush();
out.close();
// 关闭输入流
br.close();
}
/**
* 使用BFS算法计算从数字10到其他数字的最小步数
* 可以进行的操作包括:+1, -1, +10, -10, +100, -100
* 特殊情况:可以直接跳到数字10或300
*/
private static void bfs(){
// 初始化dist数组,-1表示未访问
Arrays.fill(dist,-1);
// 创建队列用于BFS遍历
Queue<Integer> queue = new LinkedList<>();
// 设置起点数字10的步数为0
dist[10]=0;
// 将起点加入队列
queue.add(10);
// 定义可能的操作数组
int[] ops = {1,-1,10,-10,100,-100};
// 当队列不为空时继续遍历
while (!queue.isEmpty()){
// 取出队首元素
int u = queue.poll();
// 创建邻居列表
List<Integer> neighbors = new ArrayList<>();
// 应用所有可能的操作生成邻居
for(int op:ops){
neighbors.add(u+op);
}
// 添加特殊邻居:10和300
neighbors.add(10);
neighbors.add(300);
// 遍历所有邻居
for(int v:neighbors){
// 如果邻居在有效范围内且未被访问过
if(v>=10&&v<=300&&dist[v]==-1){
// 更新步数
dist[v]=dist[u]+1;
// 将邻居加入队列
queue.add(v);
}
}
}
}
}
查看13道真题和解析