Codeforces 1454A (A. Special Permutation) (DFS)

A. Special Permutation
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given one integer nn (n>1n>1).

Recall that a permutation of length nn is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation of length 55, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).

Your task is to find a permutation pp of length nn that there is no index ii (1in1≤i≤n) such that pi=ipi=i (so, for all ii from 11 to nn the condition piipi≠i should be satisfied).

You have to answer tt independent test cases.

If there are several answers, you can print any. It can be proven that the answer exists for each n>1n>1.

Input

The first line of the input contains one integer tt (1t1001≤t≤100) — the number of test cases. Then tt test cases follow.

The only line of the test case contains one integer nn (2n1002≤n≤100) — the length of the permutation you have to find.

Output

For each test case, print nn distinct integers p1,p2,,pnp1,p2,…,pn — a permutation that there is no index ii (1in1≤i≤n) such that pi=ipi=i (so, for all ii from 11 to nn the condition piipi≠i should be satisfied).

If there are several answers, you can print any. It can be proven that the answer exists for each n>1n>1.

Example
input
Copy
2
2
5
output
Copy
2 1
2 1 5 3 4

 1 //2021-03-11 09:25:03
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 const int N = 1001;
 8 int T, n;
 9 bool vis[N];
10 int a[N];
11 
12 bool dfs(int tot){
13     if(tot == n+1){
14         //printf("&&&& %d   
", tot);
15         bool fff = 0;
16         for(int i = 1; i <= n; i++){
17             printf("%d ", a[i]);
18         }printf("
");
19         return true;
20     }
21     bool flag = 0;
22 //    printf("### %d   
", tot);
23     for(int i = 1; i <= n; i++){
24         if(!vis[i]){
25             if(tot != i){
26                 a[tot] = i;
27                 //printf("a[%d] = %d
", tot, i);
28             }
29             else continue;
30             vis[i] = 1;
31             if(dfs(tot+1)){
32                 flag = 1;
33                 break;
34             }
35             vis[i] = 0;
36         } 
37     }
38     if(flag) return true;
39     else return false;
40 }
41 
42 
43 int main(){
44     scanf("%d", &T);
45     while(T--){
46         scanf("%d", &n);
47         memset(vis, 0, sizeof(vis));
48         memset(a, 0, sizeof(a));
49         dfs(1);
50     }
51     
52     return 0;
53 }
原文地址:https://www.cnblogs.com/sineagle/p/14516225.html