京东笔试ak贴 2021/9/11
第一题:键盘输入
package jdtest;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
- @author: long
- @date: 2021/9/11 20:02
- @description:
- /
public class Main1 {
public static void main(String[] args) {Scanner in = new Scanner(System.in); int n = in.nextInt(), m = in.nextInt(); int x = in.nextInt(), y = in.nextInt(), z = in.nextInt(); String[] keyboard = new String[n]; in.nextLine(); for(int i=0;i<n;i++){ keyboard[i] = in.nextLine(); } String str = in.nextLine(); char[][] keyboardChArray = new char[n][]; //将字符串转化为字符串数组 for(int i=0;i<n;i++){ keyboardChArray[i] = keyboard[i].toCharArray(); } //构建HashMap,保存每个字符的位置 Map<Character,int[]> map = new HashMap<>(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ map.put(keyboardChArray[i][j],new int[]{i,j}); } } //pre数组保存前一个字符位置 int[] pre = new int[]{0,0}; long time = 0; for(int i=0;i<str.length();i++){ //拿到新的位置 char ch = str.charAt(i); int row = map.get(ch)[0]; int col = map.get(ch)[1]; if(row == pre[0] && col == pre[1]){ //同一字符 time += z; } else if(row == pre[0] || col == pre[1]){ //同行或同列字符不转向 time += (Math.abs(row - pre[0]) + Math.abs(col - pre[1])) * x; time += z; } else{ time += y; time += (Math.abs(row - pre[0]) + Math.abs(col - pre[1])) * x; time += z; } pre[0] = row; pre[1] = col; } System.out.println(time);
}
}
第二题:systemd
package jdtest;
import java.util.*;
/**
- @author: long
- @date: 2021/9/11 19:34
- @description: 构建两个List,postList保存每个服务后继的服务列表,用来找到开启某个服务后随之开启的服务
- preList保存每个服务前继的服务列表,用来找到关闭某个服务后随之关闭的服务
- /
public class Main2 {
public static void main(String[] args) {Scanner in = new Scanner(System.in); int n = in.nextInt(); int q = in.nextInt(); List<List<Integer>> postlist = new ArrayList<>(); List<List<Integer>> prelist = new ArrayList<>(); for(int i=0;i<=n;i++){ postlist.add(new ArrayList<>()); prelist.add(new ArrayList<>()); } for(int i=1;i<=n;i++){ int c = in.nextInt(); for(int j=0;j<c;j++){ int y = in.nextInt(); postlist.get(i).add(y); prelist.get(y).add(i); } } //用一个set保存开启的服务 Set<Integer> set = new HashSet<>(); //保存每次操作结果 int[] res = new int[q]; int idx = 0; for(int i=0;i<q;i++){ int x = in.nextInt(); int y = in.nextInt(); //建立队列,将开启的服务或关闭的服务加入队列 Queue<Integer> queue = new LinkedList<>(); queue.add(y); //开启状态 if(x == 1){ while(!queue.isEmpty()){ int z = queue.poll(); set.add(z); for(Integer task : postlist.get(z)){ //如果服务已经开启了,就不要加入队列,否则产生循环依赖超时 if(!set.contains(task)){ queue.add(task); } } } res[idx++] = set.size(); } else{ //关闭状态 while(!queue.isEmpty()){ int z = queue.poll(); set.remove(z); for(Integer task : prelist.get(z)){ if(set.contains(task)){ queue.add(task); } } } res[idx++] = set.size(); } } for(int i=0;i<q;i++){ System.out.println(res[i]); }
}
}