2022.8.28 小红书笔试
第一题 使用任意一种稳定排序即可
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Q1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int id = sc.nextInt(); int[][] records = new int[n][2]; for (int i = 0; i < n; i++) { records[i][0] = i; int ans = 0; for (int j = 0; j < m; j++) { ans += sc.nextInt(); } records[i][1] = ans; } Arrays.sort(records, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if (o1[1] != o2[1]){ return o2[1] - o1[1]; } return o1[0] - o2[0]; } }); for (int i = 0; i < n; i++) { if(records[i][0] == id){ System.out.println(i); break; } } } }第二题 求满足乘积大于K的组合数
import java.util.Arrays; import java.util.Scanner; public class Q2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long k = sc.nextLong(); long[] power = new long[n]; for (int i = 0; i < n; i++) { power[i] = sc.nextLong(); } Arrays.sort(power); long ans = 0; for (int i = n - 1; i > 0; i--) { long temp = ans; for (int j = i - 1; j >= 0 ; j--) { if (power[i] * power[j] < k){ break; } ans++; } if (ans == temp){ break; } } System.out.println(ans); } }第三题 一对一
import java.util.Arrays; import java.util.Scanner; public class Q3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int ans = 0; boolean[] vis = new boolean[n + 1]; int[][] friends = new int[n + 1][2]; int[] sum = new int[n + 1]; for (int i = 0; i <= n; i++) { friends[i][0] = i; } int[][] graph = new int[n + 1][n + 1]; for (int i = 2; i <= n; i++) { int j = sc.nextInt(); graph[i][j] = 1; graph[j][i] = 1; friends[i][1]++; friends[j][1]++; sum[i]++; sum[j]++; } Arrays.sort(friends,(int[] o1, int[] o2) -> o1[1] - o2[1]); for (int i = 1; i <= n ; i++) { int index = friends[i][0]; if(!vis[index]){ vis[index] = true; int min = Integer.MAX_VALUE; int next = 0; for (int j = 1; j <= n; j++) { if (graph[index][j] == 1 && min > sum[j] && !vis[j]){ min = sum[j]; vis[next] = false; next = j; vis[next] = true; } } if (next != 0){ ans++; } } } System.out.println(ans); } }
菜鸡纪念第一次提前交卷。
前两题都很简单,最后一题虽然A了,但代码写的很差,应该有更好的。