0907携程笔试AK代码
Q1
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class P1 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); List<List<Integer>> lists = new ArrayList<>(); backtrack(lists, new boolean[n], new ArrayList<>()); int ans = 0; for (List<Integer> list : lists) ans += check(list) ? 1 : 0; System.out.println(ans); } public static void backtrack(List<List<Integer>> lists, boolean[] used, List<Integer> list) { if (list.size() == used.length) lists.add(new ArrayList<>(list)); else { for (int i = 1; i <= used.length; i++) { if (used[i - 1]) continue; list.add(i); used[i - 1] = true; backtrack(lists, used, list); list.remove(list.size() - 1); used[i - 1] = false; } } } public static boolean check(List<Integer> list) { for (int i = 1; i < list.size(); i++) { int sum = list.get(i) + list.get(i - 1); if (isPrime(sum)) return false; } return true; } public static boolean isPrime(int x) { if (x == 1 || x % 2 == 0 && x != 2) return false; for (int i = 3; i < x; i += 2) { if (x % i == 0) return false; } return true; } }
Q2
import java.util.Scanner; public class P2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(), m = scan.nextInt(); char[][] grid = new char[n][], cols = new char[m][3], rows = new char[n][3]; long ans = 0; String you = "you"; for (int i = 0; i < n; i++) grid[i] = scan.next().toCharArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int x = you.indexOf(grid[i][j]); if (x == -1) continue; rows[i][x]++; cols[j][x]++; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int idx = you.indexOf(grid[i][j]); if (idx == -1) continue; long[][] array = new long[2][2]; for (int k = 0, p = 0; k < 3; k++) { if (k != idx) { array[p][0] = rows[i][k]; array[p][1] = cols[j][k]; p++; } } ans += array[0][0] * array[1][1] + array[1][0] * array[0][1]; } } System.out.println(ans); } }
Q3
import java.util.Scanner; public class P3 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while (t-- > 0) { int n = scan.nextInt(), l = scan.nextInt(), r = scan.nextInt(); int[] array = new int[n]; long sum = 0, sl = 0, br = 0; for (int i = 0; i < n; i++) { array[i] = scan.nextInt(); sum += array[i]; if (array[i] < l) sl += (l - array[i]); else if (array[i] > r) br += (array[i] - r); } double avg = (double) sum / n; if (avg > r || avg < l) System.out.println(-1); else System.out.println(Math.max(sl, br)); } } }
Q4
import java.util.*; public class P4 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); char[] cs = scan.next().toCharArray(); int cnt = 0; long ans = 0; for (char c : cs) { cnt += c == '0' ? 1 : -1; if (cnt > 0) ans += cnt; else cnt = 0; } System.out.println(ans); } }#携程##携程笔试#