/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 384.0 KiB
#2 Accepted 6ms 628.0 KiB
#3 Accepted 19ms 628.0 KiB
#4 Accepted 7ms 532.0 KiB
#5 Accepted 7ms 532.0 KiB
#6 Accepted 7ms 580.0 KiB
#7 Accepted 7ms 532.0 KiB
#8 Accepted 10ms 536.0 KiB
#9 Accepted 12ms 668.0 KiB
#10 Accepted 20ms 532.0 KiB
#11 Accepted 37ms 712.0 KiB
#12 Accepted 41ms 580.0 KiB
#13 Accepted 19ms 712.0 KiB
#14 Accepted 19ms 712.0 KiB
#15 Accepted 17ms 700.0 KiB
#16 Accepted 17ms 532.0 KiB
#17 Accepted 14ms 532.0 KiB
#18 Accepted 7ms 648.0 KiB
#19 Accepted 4ms 600.0 KiB

Code

#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
using ll = long long;

const int N = 2000 + 7;
vector<int> spf(N); // SPF : smallest prime factor

void sieve() { //=> O(n log(log(n)))
    for (int i = 1; i < N; i++) {
        spf[i] = i;
    }
    for (int i = 2; i * i < N; i++) {
        if (spf[i] == i) {
            for (int j = i * i; j < N; j += i) {
                if (spf[j] == j) spf[j] = i;
            }
        }
    }
}

struct compareFunction {
    bool operator()(const array<int, 3>& a, const array<int, 3>& b) const {
        if(a[0] != b[0]) return a[0] > b[0];
        else if(a[1] != b[1]) return a[1] < b[1];
        return a[2] > b[2];
    }
};

void solve() {
    int n;
    cin >> n;
    if(n <= 4 or n == 6) {
        cout << -1 << endl;
        return;
    }
    multiset<array<int, 3>, compareFunction> st; // {dist prime cnt, val, i}
    for(int i = 2; i <= n; i++) {
        set<int> tmp;
        int x = i;
        while (x != 1) {
            tmp.insert(spf[x]);
            // cout << spf[x] << " ";
            x /= spf[x];
        }
        int val = 1;
        for(auto &p: tmp) val *= p;
        // cout << i << " => " << val << endl;
        st.insert({tmp.size(), val, i});
    }
    vector<int> Ans(n), Pf(n);
    auto [cnt, val, ans] = *st.begin();
    Ans[0] = ans, Pf[0] = val;
    st.erase(st.begin());
    Ans[1] = 1, Pf[1] = 1;
    int c = 2;
    while(st.size()) {
        array<int, 3> tmp = {-1, -1, -1};
        for(auto &[cnt1, val, ans]: st) {
            if(__gcd(Pf[c - 1], val) == 1 && abs(ans - Ans[c - 1]) > 1) {
                tmp = {cnt1, val, ans};
                break;
            }
        }
        if(tmp[0] == -1) {
            cout << -1 << endl;
            return;
        }
        st.erase(st.find(tmp));
        Pf[c] = tmp[1];
        Ans[c] = tmp[2];
        ++c;
    }
    for(auto &i: Ans) cout << i << " "; cout << endl;
    return;
}

int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    sieve(); // build <==
    int tc = 1;
    cin >> tc;
    for (int t = 1; t <= tc; t++) {
        // cout << "Case " << t << ": ";
        solve();
    }
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1203 D. Roy Loves Permutation
Language
C++17 (G++ 13.2.0)
Submit At
2025-06-11 21:02:36
Judged At
2025-06-11 21:02:36
Judged By
Score
100
Total Time
41ms
Peak Memory
712.0 KiB