結果

問題 No.917 Make One With GCD
ユーザー htensai
提出日時 2019-12-18 15:58:41
言語 Java
(openjdk 23)
結果
AC  
実行時間 65 ms / 2,000 ms
コード長 1,469 bytes
コンパイル時間 2,704 ms
コンパイル使用メモリ 78,088 KB
実行使用メモリ 50,592 KB
最終ジャッジ日時 2024-06-24 11:13:43
合計ジャッジ時間 5,819 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;
import java.io.*;

public class Main {
    static HashMap<Integer, Long>[] maps;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        String[] first = br.readLine().split(" ", n);
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(first[i]);
        }
        maps = new HashMap[n];
        for (int i = 0; i < n; i++) {
            maps[i] = new HashMap<Integer, Long>();
        }
        System.out.println(getCount(0, arr, -1));
    }
    
    static long getCount(int idx, int[] arr, int value) {
        if (idx >= arr.length) {
            return 0;
        }
        if (maps[idx].containsKey(value)) {
            return maps[idx].get(value);
        }
        long count = getCount(idx + 1, arr, value);
        int next;
        if (value == -1) {
            next = arr[idx];
        } else {
            next = gcd(value, arr[idx]);
        }
        if (next == 1) {
            count += (long)(Math.pow(2, arr.length - idx - 1));
        } else {
            count += getCount(idx + 1, arr, next);
        }
        maps[idx].put(value, count);
        return count;
    }
    
    static int gcd(int x, int y) {
        if (x % y == 0) {
            return y;
        } else {
            return gcd(y, x % y);
        }
    }
}
0