您的位置:首页 > 其它

UVA - 524 Prime Ring Problem (经典回溯问题)

2014-08-11 10:46 387 查看



Prime Ring Problem

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers


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 <= 16)

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.

You are to write a program that completes above process.

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


题目大意:输入正整数n,把1,2,3,……n组成一个环,使得相邻的两个整数之和均为素数。输出时从整数1开始逆时针排列,同一个换恰好输出一次。n<=16

解析:本来我是想用全排列,筛选出素数环的,但是无奈,时间效率比较低。于是参考了刘汝佳的题解敲了一遍,加深了对于回溯的认识。

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 50;
int isp
;
int A
;
int vis
;
int n;
int is_prime(int n) {
	for(int i = 2; i <= sqrt(n); i++) {
		if( n % i == 0) {
			return 0;
		}
	}
	return n;
}
void dfs(int cur) {
	if(cur == n && isp[A[0] + A[n-1]]) { //递归边界
		for(int i = 0; i < n; i++) {
			printf("%d", A[i]);
			if( i != n-1) {
				printf(" ");
			}
		}
		printf("\n");
	}else {
		for(int i = 2; i <= n; i++) {
			if( !vis[i] && isp[i+A[cur-1]] ) { //如果i没有用过,并且与前一个数之和为素数
				A[cur] = i;
				vis[i] = 1;
				dfs(cur+1);
				vis[i] = 0;
			}
		}
	}
}
int main() {
	int cas = 0;
	isp[0] = 0;
	isp[1] = 0;
	for(int i = 2; i < N; i++) {
		isp[i] = is_prime(i);
	}
	while( scanf("%d",&n) != EOF) {
		memset(vis,0,sizeof(vis));
		if(cas++) {
			printf("\n");
		}
		for(int i = 0; i < n; i++) {
			A[i] = i+1;
		}
		printf("Case %d:\n",cas);
		dfs(1);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: