C++ 代码:模拟错位循环排列问题 - 优化后的代码实现
#include <bits/stdc++.h> using namespace std; const int N = 100005; long long n, m; int a[N], pos[N];
inline long long readm(){ int f = 1; long long x = 0; char c = getchar(); while (!isdigit(c)){f = c == '-' ? -1 : 1; c = getchar();} while (isdigit(c)){x = ((x << 1) + (x << 3) + (c ^ 48)) % (n * (n - 1)); c = getchar();}//一边读入一边取模 return f * x; }
int main(){ scanf('%d', &n); m = readm(); for (int i=1; i<=n; i++) scanf('%d', &a[i]); int t = m / (n - 1), left = m % (n - 1); if (t){ for (int i=1; i<=n; i++){ a[i] = (a[i] + t) % n ? (a[i] + t) % n : n; }//统计错位造成的影响 } for (int i=1; i<=n; i++) pos[a[i]] = i; for (int i=1; i<=left; i++){ int p1 = n - (i - 1) % (n - 1), p2 = n - (i - 1) % (n - 1) - 1; swap(a[pos[p1]], a[pos[p2]]); swap(pos[p1], pos[p2]); }//手动模拟 for (int i=1; i<=n; i++) printf('%d ', a[i]); return 0; }//转换为Kotlin代码内容:import java.util.*
fun main() {
val scanner = Scanner(System.in)
val n = scanner.nextInt()
var m = scanner.nextLong()
val a = IntArray(n)
val pos = IntArray(n)
for (i in 0 until n) {
a[i] = scanner.nextInt()
}
fun readm(): Long {
var f = 1
var x: Long = 0
var c = System.`in`.read().toChar()
while (!Character.isDigit(c)) {
f = if (c == '-') -1 else 1
c = System.`in`.read().toChar()
}
while (Character.isDigit(c)) {
x = ((x shl 1) + (x shl 3) + (c.toInt() xor 48)) % (n * (n - 1)).toLong()
c = System.`in`.read().toChar()
}
return (f * x)
}
val t = m / (n - 1)
var left = m % (n - 1)
if (t != 0L) {
for (i in 0 until n) {
a[i] = (a[i] + t).rem(n).let { if (it != 0) it else n }
}
}
for (i in 0 until n) {
pos[a[i] - 1] = i
}
for (i in 0 until left) {
val p1 = n - (i - 1) % (n - 1)
val p2 = n - (i - 1) % (n - 1) - 1
val temp = a[pos[p1 - 1]]
a[pos[p1 - 1]] = a[pos[p2 - 1]]
a[pos[p2 - 1]] = temp
val tempPos = pos[p1 - 1]
pos[p1 - 1] = pos[p2 - 1]
pos[p2 - 1] = tempPos
}
for (i in 0 until n) {
print('${a[i]} ')
}
}
原文地址: https://www.cveoy.top/t/topic/o0U4 著作权归作者所有。请勿转载和采集!