import kotlin.math.max fun main(arr:Array) { val columnCount = readLine()!!.toInt() val barCount = readLine()!!.toInt() val barMap = (0 until barCount).map { readLine()!!.split(" ").map { it.toInt() - 1 } } val moveTo = (0 until columnCount).map { getGoal(it, barMap) } val groupList = mutableListOf>() var subList = mutableListOf() (0 until columnCount).forEach { a-> subList.add(a) barMap.find { it[0] == a }?: run { groupList.add(subList) subList = mutableListOf() } } if(subList.isNotEmpty()) { groupList.add(subList) } val cycleList = groupList.map { null as Int? }.toTypedArray() var numList = (0 until columnCount).map { it } for(i in (1..10000000)) { var tmp = numList.withIndex().sortedBy { moveTo[it.index] }.map { it.value } numList = tmp for(j in groupList.indices) { if(cycleList[j] != null) { continue } if(numList.withIndex().filter { it.index in groupList[j] }.all { it.index == it.value }) { cycleList[j] = i } } if(cycleList.all { it != null }) { break } } val ans = cycleList.filter { it != null }.map { it!!.toLong() }.reduce { acc, i -> getMinKoubai(acc.toLong(), i.toLong()) } println(ans) } fun getMinKoubai(num1:Long, num2:Long):Long { val kouyaku = getMaxKouyaku(num1, num2) return num1 * num2 / kouyaku } fun getMaxKouyaku(num1:Long, num2:Long):Long { if(num1 % num2 == 0L) { return num2 } return getMaxKouyaku(num2, num1%num2) } fun getGoal(column:Int, barMap:List>):Int { var current = column for((f,t) in barMap) { if(f == current) { current = t } else if(current == t) { current = f } } return current }