C. Build Permutation
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
A 00-indexed array aa of size nn is called good if for all valid indices ii (0≤i≤n−10≤i≤n−1), ai+iai+i is a perfect square††.
Given an integer nn. Find a permutation‡‡ pp of [0,1,2,…,n−1][0,1,2,…,n−1] that is good or determine that no such permutation exists.
†† An integer xx is said to be a perfect square if there exists an integer yy such that x=y2x=y2.
‡‡ An array bb is a permutation of an array aa if bb consists of the elements of aa in arbitrary order. For example, [4,2,3,4][4,2,3,4] is a permutation of [3,2,4,4][3,2,4,4] while [1,2,2][1,2,2] is not a permutation of [1,2,3][1,2,3].
Input
The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases.
The only line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the length of the permutation pp.
It is guaranteed that the sum of nn over all test cases does not exceed 105105.
Output
For each test case, output nn distinct integers p0,p1,…,pn−1p0,p1,…,pn−1 (0≤pi≤n−10≤pi≤n−1) — the permutation pp — if the answer exists, and −1−1 otherwise.
Example
input
Copy
3 3 4 7
output
Copy
1 0 2 0 3 2 1 1 0 2 6 5 4 3
Note
In the first test case, we have n=3n=3. The array p=[1,0,2]p=[1,0,2] is good since 1+0=121+0=12, 0+1=120+1=12, and 2+2=222+2=22
In the second test case, we have n=4n=4. The array p=[0,3,2,1]p=[0,3,2,1] is good since 0+0=020+0=02, 3+1=223+1=22, 2+2=222+2=22, and 1+3=221+3=22.
/*
理解题意:
给一个数字n,
该n是序列的长度,
然后序列中每一位的数用 0~n-1来填
我们要求 ai+i是一个平方数
*/
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
typedef long long LL;
bool st[N];
int res[N];
int main()
{
int t;
cin>>t;
while(t--)
{
memset(st,false,sizeof st);
memset(res,-1,sizeof res);
int n;
cin>>n;
int q=(int)sqrt(n)+1;
for(int i=q;i>=0;i--) //q是要用来平方的数
{
for(int j=n-1;j>=0;j--)
{
int r=i*i-j;
if(!st[r]&&r>=0&&r<=n-1&&res[j]==-1)
{
res[j]=r;
st[r]=true;
}
}
}
for(int i=0;i<n;i++)
{
cout<<res[i]<<" ";
}
cout<<endl;
}
return 0;
}