UVA - 524 Prime Ring Problem
#include<bits/stdc++.h> using namespace std; typedef pair<int,int>Pair; int n; bool is_prime(int x) { for(int i = 2; i <= sqrt(x); i++){ if(x % i == 0){ return false; } } return true; } void solve(int cur, int* A) { if(cur == n){ if(is_prime(A[0] + A[cur-1])){ cout << A[0]; for(int i = 1; i < n; i++) cout << " " << A[i]; cout << endl; } }else{ for(int i = 1; i <= n; i++){ if(is_prime(A[cur-1] + i)){ //符合质数条件 并且 此数尚未用 int ok = true; for(int j = 0; j < cur; j++){ if(A[j] == i){ ok = false; break; } } if(ok){ A[cur] = i; solve(cur + 1, A); } } } } } int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); int kase= 0; bool first = true; while(cin >> n){ if(first){ first = false; }else cout << endl; printf("Case %d:\n", ++kase); int A[n] = {1}; solve(1, A); } return 0; }