Let's take this question Kankan: Prime Ring Problem
just started this idea or circulation problems first, then thought ah recycling is not feasible, then it can only be recursive, but recursive how to do it? ?
Recursion
Recursion is looking for export recursive and recursive body it
recursive exports this question is to determine your last digit and the first digit (ie 1) and is not a prime number, then how to judge it?
void dfs(int num,int n)
{
int i;
if(num>=n+1&&flag[a[n]+1]==1)
{
for(i=1;i<n;i++)
{
printf("%d ",a[i]);
}
printf("%d\n",a[n]);
return ;
}
else
{
for(i=2;i<=n;i++)
{
if(visit[i]==0&&flag[a[num-1]+i])
{
visit[i]=1;
a[num]=i;
dfs(num+1,n);
visit[i]=0;
}
}return ;
}
}
num represents the number of digits here I was about to discharge, that the first few numbers, n n is the input of our
Since we properly arranged into an array of numbers a, and start with an index 1, so a total of n digital requires n + 1, the final determination that the n-th digit, flag [a [n] +1 ] indicates the final determination and a first number and the number is not a prime number.
If so, then the output of the contents of the array a
, if not, begin to judge from the number 2 n-:
1. determining whether the accessed number is
2. This number is determined and an array in a digital one is prime and
if not and it has been visited and is a prime number, then this number is marked as visited, and stored in the array a, and then recursively to find a number, and finally remember to visit marking clear, because in the end will definitely visit again backtracking.
Code
#include<stdio.h>
int prime[13]={2,3,5,7,11,13,17,19,23,29,31,37,41};
int n,flag[40]={0},visit[21]={0},a[21]={0 };
void dfs(int num,int n)
{
int i;
if(num>=n+1&&flag[a[n]+1]==1)
{
for(i=1;i<n;i++)
{
printf("%d ",a[i]);
}
printf("%d\n",a[n]);
return ;
}
else
{
for(i=2;i<=n;i++)
{
if(visit[i]==0&&flag[a[num-1]+i])
{
visit[i]=1;
a[num]=i;
dfs(num+1,n);
visit[i]=0;
}
}return ;
}
}
int main()
{
int i,k=0,count=1;
for(i=0;i<40;i++)
{
if(i==prime[k])
{
flag[i]=1;
k++;
}
}
while(scanf("%d",&n)!=EOF&&n!=0)
{
for(i=1;i<=n;i++)
{
a[i]=0;
visit[i]=0;
}
a[1]=1;visit[1]=1;
printf("Case %d:\n",count++);
if(n%2==1)
{
if(n==1) printf("1\n");
else printf("\n");
}
else
{
dfs(2,n);
printf("\n");
}
}
return 0;
}
Pay attention to the access arrays and storage arrays to zero.
Furthermore, if an odd number of inputs, it primes will not form a ring, since the prime ring is necessarily an odd number adjacent a thermocouple.
If it is, then 1 direct output 1 on it.