結果
問題 | No.101 ぐるぐる!あみだくじ! |
ユーザー |
![]() |
提出日時 | 2015-09-11 18:14:22 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 186 ms / 5,000 ms |
コード長 | 1,406 bytes |
コンパイル時間 | 1,950 ms |
コンパイル使用メモリ | 77,632 KB |
実行使用メモリ | 43,492 KB |
最終ジャッジ日時 | 2024-07-19 05:17:45 |
合計ジャッジ時間 | 9,550 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 37 |
ソースコード
import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set; public class Main { public static void swap(int[] array, int a, int b){ int tmp = array[a]; array[a] = array[b]; array[b] = tmp; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a % b); } public static long lcm(long a, long b){ return a / gcd(a, b) * b; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); final int N = sc.nextInt(); final int K = sc.nextInt(); int[] perms = new int[N]; for(int i = 0; i < N; i++){ perms[i] = i; } for(int i = 0; i < K; i++){ final int x = sc.nextInt() - 1; final int y = sc.nextInt() - 1; swap(perms, x, y); } long answer = 1; boolean[] used = new boolean[N]; while(true){ int start_pos = -1; for(int i = 0; i < N; i++){ if(!used[i]){ start_pos = i; break; } } if(start_pos < 0){ break; } //System.out.println(start_pos + " " + Arrays.toString(perms)); used[start_pos] = true; int current = start_pos; int count = 1; while(true){ current = perms[current]; if(current == start_pos){ break; } //System.out.println(current); used[current] = true; count++; } answer = lcm(answer, count); } System.out.println(answer); } }