結果

問題 No.1036 Make One With GCD 2
ユーザー htensai
提出日時 2020-06-12 18:59:24
言語 Java
(openjdk 23)
結果
AC  
実行時間 1,646 ms / 2,000 ms
コード長 2,542 bytes
コンパイル時間 2,963 ms
コンパイル使用メモリ 78,000 KB
実行使用メモリ 127,696 KB
最終ジャッジ日時 2024-09-16 14:24:55
合計ジャッジ時間 32,101 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

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

public class Main {
	public static void main (String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] first = br.readLine().split(" ");
		int n = Integer.parseInt(first[0]);
		SegmentTree st = new SegmentTree(n);
		String[] second = br.readLine().split(" ", n);
		for (int i = 0; i < n; i++) {
		    st.set(i, Long.parseLong(second[i]));
		}
		st.updateAll();
		long total = 0;
		int idx = 0;
		for (int i = 0; i < n && idx < n; i++) {
		    idx = Math.max(idx, i);
		    while (idx < n && st.query(i, idx) > 1) {
		        idx++;
		    }
		    if (idx >= n) {
		        break;
		    }
		    total += n - idx;
		}
	    System.out.println(total);
	}
	
	static class Path implements Comparable<Path> {
	    int row;
	    int col;
	    int value;
	    int count;
	    
	    public Path(int row, int col, int value, int count) {
	        this.row = row;
	        this.col = col;
	        this.value = value;
	        this.count = count;
	    }
	    
	    public int compareTo(Path another) {
	        return value - another.value;
	    }
	}
}
class SegmentTree {
    int size;
    int base;
    long[] tree;
    
    public SegmentTree(int size) {
        this.size = size;
        base = 1;
        while (base < size) {
            base <<= 1;
        }
        tree = new long[base * 2 - 1];
    }
    
    public void set(int idx, long value) {
        tree[idx + base - 1] = value;
    }
    
    public void updateAll() {
        update(0);
    }
    
    public long update(int idx) {
        if (idx >= base - 1) {
            return tree[idx];
        }
        return tree[idx] = getGCD(update(2 * idx + 1), update(2 * idx + 2));
    }
    
    public long query(int min, int max) {
        return query(min, max, 0, 0, base);
    }
    
    public long query(int min, int max, int idx, int left, int right) {
        if (min >= right || max < left) {
            return 0;
        }
        if (min <= left && right - 1 <= max) {
            return tree[idx];
        }
        long x1 = query(min, max, 2 * idx + 1, left, (left + right) / 2);
        long x2 = query(min, max, 2 * idx + 2, (left + right) / 2, right);
        return getGCD(x1, x2);
    }
    
    private long getGCD(long x, long y) {
        if (x == 0) {
            return y;
        }
        if (y == 0) {
            return x;
        }
        if (x % y == 0) {
            return y;
        } else {
            return getGCD(y, x % y);
        }
    }
 }
0