杭电 1016 Prime Ring Problem【DFS】

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34175    Accepted Submission(s): 15122


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.

杭电 1016 Prime Ring Problem【DFS】_第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.这题采用了查表法,用prime数组代替素数判断的方式,节省时间。

2.在dfs函数中新增了判断n的奇偶性,因为如果n为奇数,必定多出来一个奇数,根据奇偶性原理,奇+奇=偶,凡是偶数都不是素数,必错。

3.在judge函数中,通过循环剔除重复的成分,否则可能有重复因子(不信可以注释掉后试试)。

4.在dfs函数中没有包含首尾元素的判断,由于不可能为重,所以直接判断加和是否为素数即可。

备注:

dfs函数的t为数组角标,i为对应的数。

#include<stdio.h>
#include<string.h>
int a[20],n;
int prime[38]= 
{
    0, 0, 1, 1, 0, 1, 0, 
    1, 0, 0, 0, 1, 0, 1, 
    0, 0, 0, 1, 0, 1, 0, 
    0, 0, 1, 0, 0, 0, 0, 
    0, 1, 0, 1, 0, 0, 0,
    0, 0, 1,
};


bool judge(int last,int x){
	int i;
	if(!((a[last]+x)&1)) return 0;
	if(!prime[a[last]+x]) return 0;
	for(i=0;i<=last;i++){
		if(a[i]==x) return 0;
	}
	return 1;
}

void dfs(int t){
	int i;
	if(n&1) return;
	if(t==n){
		if(prime[a[0]+a[n-1]]){
			printf("%d",a[0]);
			for(i=1;i<n;i++){
			printf(" %d",a[i]);
		}
		printf("\n");
		}
	}
	else{
		for(i=2;i<=n;i++){
			a[t]=i;
			if(judge(t-1,i)){
				dfs(t+1);
			}
		}
	}
}

int main(){
	int k=1;
	while(~scanf("%d",&n)){
		memset(a,0,sizeof(a));
		a[0]=1;
		printf("Case %d:\n",k++);
		dfs(1);
		printf("\n");
	}
	return 0;
}

 

 

你可能感兴趣的:(杭电 1016 Prime Ring Problem【DFS】)