-
Notifications
You must be signed in to change notification settings - Fork 0
/
uva524.cpp
96 lines (76 loc) · 1.85 KB
/
uva524.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
bool isPrime(int number){
if(number == 1 || number == 0){
return false;
}
if(number == 2){
return true;
}
if(number % 2 == 0){
return false;
}
int possibleDevider = sqrt(number);
for(int i = 2; i <= possibleDevider; i++){
if(number % i == 0){
return false;
}
}
return true;
}
bool primeRing(vector<int> ring, int size){
if(ring.size() == 1){
return true;
}
for(int i = 0; i < ring.size() - 1; i++){
if(!isPrime(ring[i] + ring[i+1])){
return false;
}
}
if(ring.size() == size && !isPrime(ring[0] + ring[ring.size() - 1])){
return false;
}
return true;
}
void backtrack(vector<int> ring, int size, vector<vector<int>>& solutions){
if(!primeRing(ring, size)){
return;
}
if(ring.size() == size){
solutions.push_back(ring);
return;
}
for(int i = 2; i <= size; i++){
auto it = find(ring.begin(), ring.end(), i);
if(it == ring.end()){
ring.push_back(i);
backtrack(ring, size, solutions);
ring.pop_back();
}
}
}
int main(){
int n, counter(0);
while(cin>>n){
if(counter != 0){
cout<<endl;
}
vector<int> ring = {1};
vector<vector<int>> solutions;
backtrack(ring, n, solutions);
cout<<"Case "<<++counter<<":"<<endl;
for(int i = 0; i < solutions.size(); i++){
for(int j = 0; j < solutions[i].size(); j++){
cout<<solutions[i][j];
if(j == solutions[i].size() - 1){
cout<<endl;
}else{
cout<<" ";
}
}
}
}
}