搜索——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.


 

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时的解空间如下图:

需要注意的有两点:
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
今天早上周赛时,出了这道题,回溯过程中产生所有排列时,使用的是交换的方式,而非标记,错了两次,因为交换方式所产生的排列并非是按字典序的。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

庞老板

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值