搜索——Hdu_1016_Prime Ring Problem

2012/7/24 16:17

Prime Ring Problem

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


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.
搜索——Hdu_1016_Prime Ring Problem_第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
经典的搜索问题,例如当n=6时的解空间如下图:
搜索——Hdu_1016_Prime Ring Problem_第2张图片
需要注意的有两点:
1、当n为奇数时,不可能构成一个素数环,因为n为奇数时,这n个数中奇数比偶数多一个,也就是说必有两个奇数相邻,而素数环中的数不会出现两个奇数相邻,所以n为奇数时不需要进行搜索。
2、两个奇数的和或者两个偶数的和一定不是素数,所以在搜索时应将奇数和偶数分为两组,这样效率较高。
#include <stdio.h>

int number[2][9] =
{
	3, 5, 7, 9, 11, 13, 15, 17, 19,
	2, 4, 6, 8, 10, 12, 14, 16, 18
};

bool used[2][9];

int primeRing[20] = {1};

bool isPrimeNum(int number)
{
	for (int i = 2; i * i <= number; i++)
	{
		if (number % i == 0)
		{
			return false;
		}
	}
	return true;
}

void Backtrack(int step, int n)
{
	int i;
	if (step == n)
	{
		if (isPrimeNum(primeRing[step-1] + 1))
		{
			for (i = 0; i < n-1; i++)
			{
				printf("%d ", primeRing[i]);
			}
			printf("%d\n", primeRing[i]);
		}
		return;
	}
	for (i = 0; number[step%2][i] <= n && i < 9; i++)
	{
		if (!used[step%2][i]
			&& isPrimeNum(primeRing[step-1] + number[step%2][i]))
		{
			used[step%2][i] = true;
			primeRing[step] = number[step%2][i];
			Backtrack(step+1, n);
			used[step%2][i] = false;
		}
	}
}

int main()
{
	int n, caseNum = 1;
	while (scanf("%d", &n) != EOF)
	{
		printf("Case %d:\n", caseNum++);
		if (n % 2 == 0)
		{
			Backtrack(1, n);
		}
		printf("\n");
	}
	return 0;
}
以1为起点,顺时针和逆时针得到排列,一个环就可以得到两个,这也就是说,只用搜索一半结果,另一半也就得到了,但是处理起来不太容易。
2013/4/20
今天早上周赛时,出了这道题,回溯过程中产生所有排列时,使用的是交换的方式,而非标记,错了两次,因为交换方式所产生的排列并非是按字典序的。

你可能感兴趣的:(回溯法)