【思维】G. Special Permutation

Codeforces Round 640 (Div. 4)
G. Special Permutation

题意:输出一个全排列,要求相邻数字之差的绝对值≥2且≤4.

思路:
不难发现n必须≥4,且n=4时排列应为2 4 1 3或者 3 1 4 2,以此为基础,左右两边一偶一奇/一奇一偶逐步扩展即可,如n=6时排列应为 6 2 4 1 3 5
n为奇数的话以 3 1 4 2为基础,n为偶数的话以 2 4 1 3为基础

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        if (n < 4) {
            cout << "-1" << endl;
            continue;
        }
        int i = n;
        if (i % 2 == 0) {
            while (i >= 6) {
                cout << i << " ";
                i -= 2;
            }
            cout << "2 4 ";
            for (int j = 1; j <= n - 1; j+=2) cout << j << " ";
        }
        else {
            while (i >= 1) {
                cout << i << " ";
                i -= 2;
            }
            cout << "4 2 ";
            for (int j = 6; j <= n - 1; j+=2) cout << j << " ";
        }
        cout << endl;
    }
    return 0;
}

原文链接: https://www.cnblogs.com/streamazure/p/12866537.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    【思维】G. Special Permutation

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/347903

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午4:46
下一篇 2023年3月2日 上午4:46

相关推荐