第一题
package ccf202109; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class p1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; int max = 0; int min = 0; ArrayList<Integer> list = new ArrayList<>(); Set<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); if (!set.contains(a[i])) { set.add(a[i]); list.add(a[i]); } max += a[i]; } for (Integer value : list) { min += value; } System.out.println(max); System.out.println(min); } }
第二题(化用岛屿问题)
package ccf202109; import java.util.ArrayList; import java.util.Scanner; public class p2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n + 1]; ArrayList<Integer> list = new ArrayList<>(); int maxA = 0; list.add(0); for (int i = 1; i <= n; i++) { a[i] = sc.nextInt(); if (a[i] != a[i - 1]) { list.add(a[i]); } if (a[i] > maxA) { maxA = a[i]; } } list.add(0); int[] cnt = new int[maxA + 1]; for (int i = 1; i < list.size() - 1; i++) { if (list.get(i) > list.get(i - 1) && list.get(i) > list.get(i + 1)) { cnt[list.get(i)]++; } else if(list.get(i) < list.get(i - 1) && list.get(i) < list.get(i + 1)){ cnt[list.get(i)]--; } } int max = 0; int sum = 0; for (int i = cnt.length - 1; i > 0; i--) { sum += cnt[i]; if (sum > max) { max = sum; } } System.out.println(max); } }