結果

問題 No.826 連絡網
ユーザー neko_the_shadowneko_the_shadow
提出日時 2019-05-07 11:49:25
言語 Java21
(openjdk 21)
結果
TLE  
実行時間 -
コード長 1,880 bytes
コンパイル時間 2,382 ms
コンパイル使用メモリ 75,868 KB
実行使用メモリ 764,140 KB
最終ジャッジ日時 2023-09-14 16:25:57
合計ジャッジ時間 26,271 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 125 ms
55,720 KB
testcase_01 AC 126 ms
55,976 KB
testcase_02 AC 168 ms
58,280 KB
testcase_03 AC 1,095 ms
231,048 KB
testcase_04 TLE -
testcase_05 AC 411 ms
115,652 KB
testcase_06 AC 423 ms
115,408 KB
testcase_07 AC 1,733 ms
358,856 KB
testcase_08 AC 511 ms
132,776 KB
testcase_09 TLE -
testcase_10 AC 223 ms
68,140 KB
testcase_11 AC 849 ms
191,900 KB
testcase_12 MLE -
testcase_13 MLE -
testcase_14 MLE -
testcase_15 MLE -
testcase_16 MLE -
testcase_17 MLE -
testcase_18 MLE -
testcase_19 MLE -
testcase_20 MLE -
testcase_21 TLE -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
testcase_30 -- -
testcase_31 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        int n = stdin.nextInt();
        int p = stdin.nextInt();
        Main main = new Main(n, p);
        
        System.out.println(main.solve());
    }
    
    private int n;
    private int p;
    private int[][] cache;
    
    public Main(int n, int p) {
        this.n = n;
        this.p = p;
        this.cache = new int[n + 1][n + 1];
    }
    
    public int solve() {
        UnionFind uf = new UnionFind(n);
        for (int x = 0; x < n; x++) {
            for (int y = x + 1; y < n; y++) {
                if (gcd(x + 1, y + 1) != 1) {
                    uf.union(x, y);
                }
            }
        }
        return uf.size(p - 1);
    }
    
    public int gcd(int x, int y) {
        if (cache[x][y] != 0) {
            return cache[x][y];
        }
        
        cache[x][y] = (x < y)      ? gcd(y, x)    :
                      (x % y == 0) ? y            :
                                     gcd(y, x % y);
        return cache[x][y];
     
    }
}

class UnionFind {
    
    private int[] parents;
    private int[] sizes;
    
    public UnionFind(int n) {
        parents = IntStream.range(0, n).toArray();
        sizes = new int[n];
        Arrays.fill(sizes, 1);
    }
    
    public void union(int x, int y) {
        x = find(x);
        y = find(y);
        
        if (x != y) {
            sizes[y] += sizes[x];
            parents[x] = y;
        }
    }
    
    public int find(int x) {
        if (parents[x] == x) {
            return x;
        } else {
            parents[x] = find(parents[x]);
            return parents[x];
        }
    }
    
    public int size(int x) {
        return sizes[find(x)];
    }
}
0