米哈游笔试记录
1 括号匹配
#米哈游##笔经#
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
StringBuilder buf = new StringBuilder();
while(T-- > 0) {
String s = sc.next();
Stack<Character> stack = new Stack<>();
int count = 0;
for (int i = 0; i < s.length(); ++i) {
if (stack.isEmpty() || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.add(s.charAt(i));
} else {
if (s.charAt(i) == ']' && stack.peek() == '['
|| stack.peek() == '{' && s.charAt(i) == '}') {
} else {
count++;
}
stack.pop();
}
}
buf.append(count).append("\n");
}
System.out.print(buf);
}
} 2 组合数学中的插板法
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
StringBuilder buf = new StringBuilder();
while(T-- > 0) { // 10^4
int n = sc.nextInt() / 3; // 10^5
int count = (int)((long)(n-1)*(n-2) / 2);
buf.append(count).append("\n");
}
System.out.print(buf);
}
} 3 BFS import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r1 = sc.nextInt();
int c1 = sc.nextInt();
int r2 = sc.nextInt();
int c2 = sc.nextInt();
System.out.println(game(r1, c1, r2, c2));
}
public static int game(int r1, int c1, int r2, int c2) {
if (r1 == r2 && c1 == c2) {
return 0;
}
int[][] pos = new int[10][9];
pos[r1][c1] = 1;
Queue<Integer> que = new LinkedList<>();
que.add(r1 * 10 + c1);
int[][] dir = {{-3, -2}, {-2, -3}, {2, -3}, {3, -2},
{3, 2}, {2, 3}, {-2, 3}, {-3, 2}};
while (!que.isEmpty()) {
int xy = que.remove();
int x = xy / 10;
int y = xy % 10;
for (int i = 0; i < 8; ++i) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (xx >= 0 && xx < 10 && yy >= 0 && yy < 9 && pos[xx][yy] == 0) {
if (xx == r2 && yy == c2) {
return pos[x][y];
}
int nextX = x + dir[i][0] / 3;
int nextY = y + dir[i][1] / 3;
if (nextX == r2 && nextY == c2) {
continue;
} else {
nextX = nextX + xx >> 1;
nextY = nextY + yy >> 1;
if (nextX == r2 && nextY == c2) {
continue;
}
}
pos[xx][yy] = pos[x][y] + 1;
que.add(xx * 10 + yy);
}
}
}
return -1;
}
} 