-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUva524 - Prime Ring Problem.cpp
More file actions
64 lines (56 loc) · 1.61 KB
/
Uva524 - Prime Ring Problem.cpp
File metadata and controls
64 lines (56 loc) · 1.61 KB
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
#include<bits/stdc++.h>
#define bug cout<<"bug";
#define pb(n) push_back(n)
#define lli long long int
#define fr(i,s,l) for(i=s;i<l;i++)
#define sf(n) scanf("%d",&n);
#define nl printf("\n")
#define mst(n) memset(n,0,sizeof(n))
// a straight-forward backtracking problem , checking all possible combination that meets the requirement
using namespace std;
vector<int> show;
bool vis[10000];
int prime[13]= {1,2,3,5,7,11,13,17,19,23,29,31,37}; //as input range is small , all the prime numbers have been taken in array
int backTrack(int num)
{
if(find(prime,prime+13,show.rbegin()[1]+show.back())==prime+13) // checking if sum of 2 consecutive numbers is prime
{
return 0;
}
if(show.size()==num+1)
{
if(find(prime,prime+13,show.back()+1)==prime+13) return 0; //as this is a circle so the last element is a neighbor element of the first element (1) ,,so primality test of sum is done here
for(int j=1; j<=num; j++)
{
printf("%d",show[j]);
if(j!=num)
printf(" ");
}
nl;
return 0;
}
for(int i=2; i<=num; i++)
{
if(!vis[i])
{
vis[i]=1;
show.push_back(i);
backTrack(num);
vis[i]=0, show.pop_back();
}
}
}
int main()
{
int i=1;
int n;
while(scanf("%d",&n)==1)
{
if(i>1) nl;
show.push_back(0);
show.push_back(1);
printf("Case %d:\n",i++);
backTrack(n);
show.clear(),mst(vis);
}
}