1 solutions

  • 0
    @ 2026-8-21 9:26:39

    简单构造:题解

    除去少数连接位置,我们让相邻两数之和恒为 2(mod4)2\pmod 4。完全平方数模 44 只能为 00 或 11,所以这样的和一定不是平方数。

    当 n≥5n\ge5 时,按以下顺序输出:

    1. 所有偶数降序;
    2. 11;
    3. 所有大于 55 且模 44 余 11 的数;
    4. 5,35,3;
    5. 所有大于 33 且模 44 余 33 的数。

    同一类中相邻两数之和为 2(mod4)2\pmod4;各段连接处分别是“2+12+1”、两个模 44 余 11 的数、“5+35+3”以及两个模 44 余 33 的数,均不可能为平方数。

    n=1,2,3,4n=1,2,3,4 分别直接构造即可。时间复杂度为 O(n)O(n),除输出数组外空间复杂度为 O(n)O(n);也可以边生成边输出做到 O(1)O(1) 额外空间。

    参考实现(C++17)

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
        ios::sync_with_stdio(false); cin.tie(nullptr);
        int T; if(!(cin>>T)) return 0;
        while(T--){
            int n; cin>>n;
            vector<int> p;
            p.reserve(n);
            if(n==1) p={1};
            else if(n==2) p={2,1};
            else if(n<=4){ for(int i=1;i<=n;++i)p.push_back(i); }
            else{
                for(int x=(n/2)*2;x>=2;x-=2)p.push_back(x);
                p.push_back(1);
                for(int x=9;x<=n;x+=4)p.push_back(x);
                p.push_back(5);
                p.push_back(3);
                for(int x=7;x<=n;x+=4)p.push_back(x);
            }
            for(int i=0;i<n;++i){ if(i)cout<<' '; cout<<p[i]; }
            cout<<'\n';
        }
    }
    

    Information

    ID
    228
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    8
    Tags
    # Submissions
    51
    Accepted
    7
    Uploaded By