結果
| 問題 | No.101 ぐるぐる!あみだくじ! | 
| コンテスト | |
| ユーザー |  ぴろず | 
| 提出日時 | 2014-12-11 23:38:59 | 
| 言語 | Java (openjdk 23) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 250 ms / 5,000 ms | 
| コード長 | 961 bytes | 
| コンパイル時間 | 2,465 ms | 
| コンパイル使用メモリ | 76,700 KB | 
| 実行使用メモリ | 43,392 KB | 
| 最終ジャッジ日時 | 2024-06-11 20:42:06 | 
| 合計ジャッジ時間 | 11,328 ms | 
| ジャッジサーバーID (参考情報) | judge1 / judge2 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 37 | 
ソースコード
package no101;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		int[] a = new int[n];
		for(int i=0;i<n;i++) {
			a[i] = i;
		}
		for(int i=0;i<k;i++) {
			int x = sc.nextInt() - 1;
			int y = sc.nextInt() - 1;
			int temp = a[x];
			a[x] = a[y];
			a[y] = temp;
		}
		boolean[] used = new boolean[n];
		long ans = 1;
		for(int i=0;i<n;i++) {
			if (used[i]) {
				continue;
			}
			int length = 0;
			int now = i;
			while(true) {
				if (used[now]) {
					break;
				}
				used[now] = true;
				length++;
				now = a[now];
			}
			ans = lcm(ans, length);
		}
		System.out.println(ans);
	}
	public static long gcd(long a,long b) {
		while(b!=0) {
			long r = a%b;
			a = b;
			b = r;
		}
		return a;
	}
	public static long lcm(long a,long b) {
		return a * b / gcd(a,b);
	}
}
            
            
            
        