Prime Ring Problem (backtracking method)

A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.

Input

n (0 < n < 20).

Output

The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.

You are to write a program that completes above process.

Print a blank line after each case.

Sample Input

6
8

Sample Output

Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

Ideas:

Backtracking, this is similar to the "n-queen" problem.

This algorithm uses stairs to describe it vividly: when you stand on a certain level, judge whether you have reached the ground (it ends when you reach the ground). If you do not reach the ground, then consider which level you want to go down to (restricted in the title). And record (book), and finally return to zero

Implementation code:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,a[50],book[50];/*这里的a对应输出的数*/
int prime(int x)/*判断素数,是素数返回1*/
{
	for(int i=2;i*i<=x;i++)
	{
		if(x%i==0)return 0;
	}
	return 1;
}
void dfs(int y)
{
	if(y==n&&prime(1+a[n-1])==1)/*判断环里面最后一个数和第一个数1的和是否为素数*/
	{
		printf("1");
		for(int i=1;i<=n-1;i++)
		{
			printf(" %d",a[i]);
		}
		printf("\n");
	}
	for(int i=2;i<=n;i++)
	{
		if(!book[i]&&prime(a[y-1]+i)==1)
		{
			a[y]=i;
			book[i]=1;
			dfs(y+1);
			book[i]=0;/*这里的最后归零很重要!!*/
		}
	} 
}
int main()
{
	int k=0;
	while(~scanf("%d",&n))
	{
		printf("Case %d:\n",++k);
		memset(book,0,sizeof(book));
		a[0]=1;
		dfs(1);
		printf("\n");	/*格式需要*/
	}
	return 0;
}

Note: Format! At the beginning, Ajiu put printf("\n"); /*format needs*/ in printf("Case %d:\n",++k); above: if(k>0)printf( "\n");/*Format needs*/ Submit, Presentation Error. So pay attention to the format QQ

Supplement: function to determine prime numbers (more efficient)

int is_prime(int x)

{
    for (int i = 2; i*i  <= x; i++)
    if (x % i == 0) return 0;
    return 1;
}

 

Guess you like

Origin blog.csdn.net/with_wine/article/details/113954109