fun problem160d(n: Int, x: Int, y: Int): String { val routes = Array(n) { mutableListOf<Int>() } for (i in 0 until n - 1) { routes[i].add(i + 1) routes[i + 1].add(i) } routes[x - 1].add(y - 1) routes[y - 1].add(x - 1) val distances= Array(n - 1) { IntArray(n) { -1 } } val counts = hashMapOf<Int, Int>() for (i in 0 until n - 1) { val queue = ArrayDeque<Int>() queue.offer(i) distances[i][i] = 0 while(!queue.isEmpty()) { val current = queue.poll() for (j in 0 until routes[current].size) { val next = routes[current][j] if (distances[i][next] != -1) continue distances[i][next] = distances[i][current] + 1 queue.offer(next) } } distances[i] = distances[i].drop(i + 1).toIntArray() for (j in 0 until distances[i].size) { counts[distances[i][j] + 1] = (counts[distances[i][j] + 1] ?: 0) + 1 } } val ans = Array(n - 1) { 0 } var count = 0 for (i in counts) { ans[count] = i.value count++ } return ans.joinToString("\n") } val routes = Array(n) { mutableListOf<Int>() } for (i in 0 until n - 1) { routes[i].add(i + 1) routes[i + 1].add(i) } routes[x - 1].add(y - 1) routes[y - 1].add(x - 1) distances[i] = distances[i].drop(i + 1).toIntArray() for (j in 0 until distances[i].size) { counts[distances[i][j] + 1] = (counts[distances[i][j] + 1] ?: 0) + 1 } debug: [[3, 2, 1, 0, 1, 2, 2]] fun problem160d(n: Int, x: Int, y: Int): String { val dist = Array(n) { IntArray(n) { -1 } } for (s in 0 until n) { val que = ArrayDeque<Int>() que.offer(s) dist[s][s] = 0 while (!que.isEmpty()) { val v = que.poll() val nvs = mutableListOf<Int>() if (v > 0) nvs.add(v - 1) if (v < n - 1) nvs.add(v + 1) if (v == x - 1) nvs.add(y - 1) if (v == y - 1) nvs.add(x - 1) for (nv in nvs) { if (dist[s][nv] == -1) { dist[s][nv] = dist[s][v] + 1 que.offer(nv) } } } } val res = IntArray(n) { 0 } for (i in 0 until n) { for (j in i + 1 until n) { res[dist[i][j]]++ } } return res.drop(1).joinToString("\n") } fun problem160d(n: Int, x: Int, y: Int): String { val ans = IntArray(n - 1) { 0 } for (i in 1 until n) { for (j in i + 1 until n + 1) { debugLog("i", i, "j", j, j - i, abs(i - x) + 1 + abs(j - y), "min:", min(j - i, abs(i - x) + 1 + abs(j - y))) val distance = min(j - i, abs(i - x) + 1 + abs(j - y)) ans[distance - 1]++ } } return ans.joinToString("\n") } debug: [i, 1, j, 2, 1, 8, min:, 1] 1 to 2, 1が採用される debug: [i, 1, j, 3, 2, 7, min:, 2] 1 to 3, 2が採用される debug: [i, 1, j, 4, 3, 6, min:, 3] 1 to 4, 3が採用される debug: [i, 1, j, 5, 4, 5, min:, 4] 1 to 5, 4が採用される debug: [i, 1, j, 6, 5, 4, min:, 4] 1 to 6, 4が採用される!これは7まで行って戻った方が早いからだ。 debug: [i, 1, j, 7, 6, 3, min:, 3] 1 to 7, 3が採用される!これはショートカットを使って7まで行けば済むからだ。