/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 2ms 824.0 KiB
#2 Time Exceeded ≥1600ms ≥532.0 KiB
#3 Time Exceeded ≥1600ms ≥576.0 KiB

Code

#include <bits/stdc++.h>
using namespace std;

int n;
vector<int> result;
vector<bool> used;
bool found = false;

bool isValid(int a, int b) {
    return __gcd(a, b) == 1 && abs(a - b) > 1;
}

void dfs(vector<int>& path) {
    if (found) return; // early exit
    if (path.size() == n) {
        result = path;
        found = true;
        return;
    }

    for (int i = 1; i <= n; ++i) {
        if (!used[i]) {
            if (!path.empty()) {
                if (!isValid(path.back(), i)) continue;
            }
            used[i] = true;
            path.push_back(i);
            dfs(path);
            path.pop_back();
            used[i] = false;
        }
    }
}

void solve(int N) {
    n = N;
    result.clear();
    used.assign(n + 1, false);
    found = false;
    vector<int> path;
    dfs(path);

    if (found) {
        for (int x : result) cout << x << " ";
        cout << endl;
    } else {
        cout << -1 << endl;
    }
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        int N;
        cin >> N;
        solve(N);
    }
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1203 D. Roy Loves Permutation
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-16 21:04:48
Judged At
2025-07-16 21:04:48
Judged By
Score
2
Total Time
≥1600ms
Peak Memory
≥824.0 KiB