ABC248 D問題を解いているのですが、どうしても処理時間のパフォーマンスが上がらずTLEになってしまうため、改善点を教えていただきたいです。
実際のコードについて以下となります。
Java
1 import java.util.*; 2 3 public class Main { 4 5 static int n; 6 7 public static void main(String[] args) { 8 Scanner sc = new Scanner(System.in); 9 10 n = sc.nextInt(); 11 int[] as = getMultipleNumbers(sc, n); 12 13 int q = sc.nextInt(); 14 15 Map<Integer, List<List<Integer>>> qMap = new HashMap<>(n + 1, 2); 16 17 for (int i = 0; i < q; i++) { 18 int l = sc.nextInt(); 19 int r = sc.nextInt(); 20 int x = sc.nextInt(); 21 addXandI(qMap, i, l - 1, x, 0); 22 addXandI(qMap, i, r, x, 1); 23 } 24 25 long[] res = new long[q]; 26 long[] cnt = new long[n + 1]; 27 for (int i = 1; i <= n; i++) { 28 int ai = as[i]; 29 cnt[ai]++; 30 31 if (!qMap.containsKey(i)) continue; 32 33 List<List<Integer>> queues = qMap.get(i); 34 for (List<Integer> qu : queues) { 35 Integer x = qu.get(0); 36 Integer idx = qu.get(1); 37 Integer isR = qu.get(2); 38 if (isR == 1) { 39 res[idx] += cnt[x]; 40 } else { 41 res[idx] -= cnt[x]; 42 } 43 } 44 } 45 46 for (long r : res) { 47 System.out.println(r); 48 } 49 } 50 51 private static void addXandI(Map<Integer, List<List<Integer>>> qMap, int i, int lr, int x, int isR) { 52 List<List<Integer>> orDefault = qMap.getOrDefault(lr, new ArrayList<>()); 53 orDefault.add(Arrays.asList(x, i, isR)); 54 qMap.put(lr, orDefault); 55 orDefault = null; 56 } 57 58 private static int[] getMultipleNumbers(Scanner sc, int count) { 59 int[] nums = new int[count + 1]; 60 nums[0] = 0; 61 for (int i = 1; i <= count; i++) { 62 nums[i] = sc.nextInt(); 63 } 64 65 return nums; 66 } 67 }
提出結果は以下のURLを御覧ください。
https://atcoder.jp/contests/abc248/submissions/31458595
解法については以下の解説を参考にしており、処理量は十分少ないと考えております。
https://atcoder.jp/contests/abc248/editorial/3821
そのため、Map<Integer, List<List<Integer>>>
というような強引なデータ構造がパフォーマンスを落としているのだろうか、とは考えております。
アドバイスをいただけますと幸いです。
以上、よろしくお願いいたします。
あなたの回答
tips
プレビュー