John Doe has found the beautiful permutation formula.
Let's take permutation p = p1, p2, ..., pn. Let's define transformation f of this permutation:
where k (k > 1) is an integer, the transformation parameter, r is such maximum integer that rk ≤ n. If rk = n, then elements prk + 1, prk + 2 and so on are omitted. In other words, the described transformation of permutation p cyclically shifts to the left each consecutive block of length k and the last block with the length equal to the remainder after dividing n by k.
John Doe thinks that permutation f(f( ... f(p = [1, 2, ..., n], 2) ... , n - 1), n) is beautiful. Unfortunately, he cannot quickly find the beautiful permutation he's interested in. That's why he asked you to help him.
Your task is to find a beautiful permutation for the given n. For clarifications, see the notes to the third sample.
A single line contains integer n (2 ≤ n ≤ 106).
Print n distinct space-separated integers from 1 to n — a beautiful permutation of size n.
2
2 1
3
1 3 2
4
4 2 3 1
A note to the third test sample:
- f([1, 2, 3, 4], 2) = [2, 1, 4, 3]
- f([2, 1, 4, 3], 3) = [1, 4, 2, 3]
- f([1, 4, 2, 3], 4) = [4, 2, 3, 1]
在每次变换的时候,都是取一个长度是t的区间,然后把区间的第一个元素放末尾
那么只要每次把所有这样长度为t的区间的a[kt+1]放到a[kt+t+1]即可。
比如样例的变换:
1 2 3 4 0 0 0
0 2 1 4 3 0 0
0 0 1 4 2 3 0
0 0 0 4 2 3 1
这样每次元素在数组当中的位置都会往后移一位,但是总长度还是n
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<cstdlib> 5 #include<algorithm> 6 #include<cmath> 7 #include<queue> 8 #include<deque> 9 #include<set> 10 #include<map> 11 #include<ctime> 12 #define LL long long 13 #define inf 0x7ffffff 14 #define pa pair<int,int> 15 #define mkp(a,b) make_pair(a,b) 16 #define pi 3.1415926535897932384626433832795028841971 17 using namespace std; 18 inline LL read() 19 { 20 LL x=0,f=1;char ch=getchar(); 21 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 22 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 23 return x*f; 24 } 25 int n; 26 int a[2000010]; 27 int main() 28 { 29 while (~scanf("%d",&n)) 30 { 31 for (int i=1;i<=n;i++)a[i]=i; 32 for (int k=2;k<=n;k++) 33 { 34 int ed=n+k-1,rp=n/k+(n%k!=0); 35 for (int t=k-1+(rp-1)*k;t>=k-1;t-=k) 36 { 37 swap(a[ed],a[t]); 38 ed=t; 39 } 40 } 41 for (int i=n;i<=2*n-1;i++)printf("%d ",a[i]); 42 puts(""); 43 } 44 }