阿里巴巴java后端实习 3.29笔试复盘
题目写了个大概,仅供自己记录~
1、题目大致有n个人投票,每个人可以投k票,已知这n个人投给小明的票数分别是ai,则k最少为多少可以保证我获胜
输入:
5
2 2 2 3 4
输出:
6
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(n < 1) return; int[] other = new int[n]; int sum = 0,sumMe = 0,k=0; for (int i = 0; i < n; i++) { other[i] = sc.nextInt(); sum+= other[i]; k = Math.max(k, other[i]); } sumMe = getTotal(other,k); for (int i = k;; i++) { if(sumMe > sum) { System.out.println(i); break; }else { sumMe += n; } } } private static int getTotal(int[] other, int k) { int sum = 0; for (int i = 0; i < other.length; i++) { sum += (k-other[i]); } return sum; }2、有n个车站,m条路,接着输出车站a、b之间的距离,从某个车站出发可以到达的最少的车站,如果个数一样,输出编号大的车站
第二题没ac,只是记录
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int d = sc.nextInt(); // 输入m行数据 int[][] matrix = new int[n][n]; boolean[][] flag = new boolean[n][n]; for (int k = 1; k <= m; k++) { int i = sc.nextInt(); int j = sc.nextInt(); int w = sc.nextInt(); matrix[i][j] = w; matrix[j][i] = w; flag[i][j] = true; flag[j][i] = true; } // 初始化到达矩阵 for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (i == j) { matrix[i][j] = 0; flag[i][j] = true; } else if (matrix[i][j] == 0) { flag[i][j] = false; } } } // 不能直接到达,可能可以间接到达 for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (flag[i][j] == false) { int min = Integer.MAX_VALUE; for (int k = 1; k < j; k++) { if (flag[i][k] && flag[k][j-k]) { min = Math.min(matrix[i][k] + matrix[k][j-k], min); matrix[i][j] = min; matrix[j][i] = min; flag[i][j] = true; } } } } } // 计算开始 int minCount = n, minCity = n - 1;// 最小的是城市0 for (int i = matrix.length - 1; i >= 0; i--) { int sum = 0, count = 0; for (int j = 0; j < matrix[i].length; j++) { if (!flag[i][j]) { continue; } else { if (matrix[i][j] + sum <= d) { sum += matrix[i][j]; count++; } else { continue; } } } if (minCount > count) { minCount = count; minCity = i; } } System.out.println(minCity); } }