codeforces #686 div3 A. Special Permutation(找规律)

A. Special Permutation
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given one integer n (n>1).

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

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

You have to answer t independent test cases.

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

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

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

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

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

Example
inputCopy
2
2
5
outputCopy
2 1
2 1 5 3 4
题意:有n个正整数,打乱其排列,使原来的数不能在自己最开始的位置。
题解:分奇数和偶数进行讨论,偶数,只要该n个数逆序输出,那么一定保证该数字不会出现在原来的位置。
奇数,先找到这一组数中的最后一个数放在输出的中间--------记做mid,剩下的偶数个数的前半部分放在mid的后面进行输出,后半部分放在mid前面输出。
本题即可求解。
样例输出的顺序是有误导性的,会引到前半部分逆序输出,接着输出最后一个数,在按照顺序输出剩下的。---------------------这个思路严重错误!!!!!!!!

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
    std::ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
    
    
        int n;
        int a[100];
        memset(a,0,sizeof(a));
        cin>>n;
        for(int i=0;i<n;i++)
        {
    
    
            a[i]=i+1;
        }
        if(n%2==0)//偶数
        {
    
    
            for(int i=n-1;i>=0;i--)
            {
    
    
                if(i!=0)
                {
    
    
                    printf("%d ",a[i]);
                }
                else
                {
    
    
                    printf("%d\n",a[i]);
                }
                
            }
        }
        if(n&1)//奇数
        {
    
    
             for(int i=n/2;i<n-1;i++)
            {
    
    
                printf("%d ",a[i]);
            }
             printf("%d ",a[n-1]);
             for(int i=0;i<n/2;i++)
            {
    
    
                if(i!=n/2-1)
                printf("%d ",a[i]);
                else
                {
    
    
                    printf("%d\n",a[i]);                }
                
            }
        }
    }
   // system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46006714/article/details/110103271
今日推荐