第一题
package ccf201712; import java.util.ArrayList; import java.util.Scanner; public class p1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; ArrayList<Integer> res = new ArrayList<>(); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int min = 10001; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int num = Math.abs(a[i] - a[j]); if (min > num) { min = num; } } } res.add(min); System.out.println(res.get(0)); } }
第二题(k的值为1时需要特判,该题陷阱之一)
package ccf201712; import java.util.Scanner; public class p2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); if (k == 1) { System.out.println(n); } else { int[] list = new int[n + 1]; for (int i = 1; i < n + 1; i++) { list[i] = 1; } int count = 0; int num = n; do { for (int i = 1; i <= n; i++) { if (list[i] == 1) { count++; if (count % k == 0 || (count % 10) == k) { list[i] = 0; num--; } } } } while (num != 1); for (int i = 0; i < n; i++) { if (list[i] == 1) { System.out.println(i); } } } } }