結果

問題 No.101 ぐるぐる!あみだくじ!
ユーザー htensai
提出日時 2020-05-14 17:16:56
言語 Java
(openjdk 23)
結果
AC  
実行時間 203 ms / 5,000 ms
コード長 959 bytes
コンパイル時間 2,454 ms
コンパイル使用メモリ 77,536 KB
実行使用メモリ 43,272 KB
最終ジャッジ日時 2024-09-15 11:55:11
合計ジャッジ時間 11,296 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
	public static void main (String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < n; i++) {
		    arr[i] = i;
		}
		for (int i = 0; i < k; i++) {
		    int x = sc.nextInt() - 1;
		    int y = sc.nextInt() - 1;
		    int tmp = arr[x];
		    arr[x] = arr[y];
		    arr[y] = tmp;
		}
		int[] idxes = new int[n];
		for (int i = 0; i < n; i++) {
		    idxes[arr[i]] = i;
		}
		long ans = 1;
		for (int i = 0; i < n; i++) {
		    int count = 1;
		    int x = i;
		    while (i != idxes[x]) {
		        x = idxes[x];
		        count++;
		    }
		    ans = getLCM(ans, count);
		}
		System.out.println(ans);
	}
	
	static long getLCM(long x, long y) {
	    return x / getGCD(x, y) * y;
	}
	
	static long getGCD(long x, long y) {
	    if (x % y == 0) {
	        return y;
	    } else {
	        return getGCD(y, x % y);
	    }
	}
}
0