HDU-1016Prime Ring Problem(素数环问题-dfs深搜)

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Problem Description
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


题目大意是:对于1到n的数求它的所有排列使得每个数与之相邻的数之和为素数(质数)
我们可以先将题目范围的数据判断一下i是否为素数,这里的数据比较小,所以用不着素数筛。然后在dfs排列的时候简单判断一下该数与旁边的相加是否为素数。

if (!v[i] && prim[i+a[k-1]])

因为我们是一个一个的将数放入,所以只需判断与左边的是否满足条件就行了,不需要进行两边判断。具体代码如下

#include <cstdio>
#include <cmath>
#include <cstring>
void dfs(int k);
void print();
int prim[40]= {0};
int n,v[50]= {0},a[20],t=0;
int main() {
	for (int i=2; i<=45; i++) {
		int j;
		for (j=2; j<=sqrt(i); j++)
			if (i%j==0) break;
		if (j>sqrt(i)) prim[i]=1;
	}
	while (scanf ("%d",&n)!=EOF) {
		t++;
		a[1]=1;
		v[1]=1;
		printf ("Case %d:\n",t);
		dfs(2);
		printf ("\n");
		memset(a,0,sizeof(a));
		memset(v,0,sizeof(v));
	}
	return 0;
}
void dfs(int k) {
	if (k==n+1 && prim[a[n]+a[1]]) print();
	else {
		for (int i=2; i<=n; i++) {
			if (!v[i] && prim[i+a[k-1]]) {
				a[k]=i;
				v[i]=1;
				dfs(k+1);
				v[i]=0;
				a[k]=0;
			}
		}
	}
}
void print() {
	for (int i=1; i<n; i++)
		printf ("%d ",a[i]);
	printf ("%d\n",a[n]);

}

猜你喜欢

转载自blog.csdn.net/qq_43906000/article/details/88289554