【題解】UVA-524 Prime Ring Problem

【題目敘述】https://vjudge.net/problem/UVA-524

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

int t, n, p[35], used[20];
vector <int> ans;

void f(int x){
    if (x > n){
        if (p[*ans.begin()+ans.back()]) return;
        cout << ans[0];
        for (int i = 1; i < ans.size(); i++){
            cout << " " << ans[i];
        }
        cout << "\n";
    }
    for (int i = 1; i <= n; i++){
        if (used[i]) continue;
        if (!p[i+ans.back()]){
            used[i] = 1;
            ans.push_back(i);
            f(x+1);
            used[i] = 0;
            ans.pop_back();
        }
    }
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    for (int i = 2; i <= 32; i++){
        if (!p[i]){
            for (int j = i*2; j <= 32; j += i){
                p[j] = 1;
            }
        }
    }
    int Case = 0;
    bool flag = false;
    while (cin >> n){
        if (!flag) flag = true;
        else cout << endl;
        memset(used, 0, sizeof(used));
        used[1] = 1;
        ans.clear();
        ans.push_back(1);
        Case++;
        cout << "Case " << Case << ":\n";
        f(2);
    }
}
分享本文 Share with friends