Prime ring problem

科普

顾名思义了,英文不差的都可以直译出来,素数环问题,这里把百度百科的词条贴出来科普一下



题目

题目描述:
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.


输入:
n (1 < n < 17).
输出:
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.
样例输入:
6
8
样例输出:
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
提示:
用printf打印输出。


思路

比较简单的dfs深度优先搜索+回溯法

AC代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int prime[35];
int visit[18];
int record[18];

void pre_process()
{
	int i, j;
	
	memset(prime, 1, sizeof(prime));
	prime[0] = prime[1] = 0;

	for (i = 2; i <= 34; i ++) {
		if (prime[i]) {
			for (j = i + i; j <= 34; j += i) {
				prime[j] = 0;
			}
		}
	}
}

void depth_first_search(int i, int n)
{
	int j;

	if (i == n && prime[1 + record[n - 1]]) { // 构成素数环(do not forge test the first data and the last data)
		for (j = 0; j < n; j ++) {
			if (j == n - 1)
				printf("%d\n", record[j]);
			else
				printf("%d ", record[j]);
		}
	} else {	// 深度优先遍历
		for (j = 2; j <= n; j ++) {
			if (visit[j] == 0 && prime[record[i - 1] + j]) { // j没有访问过,并且和前一个记录之和为素数
				record[i] = j;
				visit[j] = 1;
				depth_first_search(i + 1, n);
				visit[j] = 0;
			}
		}

	}
}


int main()
{
	int i, n;
	i = 0;
	pre_process();

	while (scanf("%d", &n) != EOF) {
		printf("Case %d:\n", ++ i);
		memset(visit, 0, sizeof(visit));
		record[0] = 1;
		visit[1] = 1;
		depth_first_search(1, n);
		printf("\n");
	}

	return 0;
}
/**************************************************************
	Problem: 1459
	User: wangzhengyi
	Language: C
	Result: Accepted
	Time:410 ms
	Memory:912 kb
****************************************************************/



posted @ 2013-05-17 19:57  java程序员填空  阅读(209)  评论(0编辑  收藏  举报