HDU 1016 Prime Ring Problem

Prime Ring Problem

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


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(0<n<20),然后将1-n排在一个圆环上面,要求每相邻的两个整数相加起来是素数。
思路:DFS+剪枝。用深搜求出所有的排列然后判断每一个排列是否满足题目要求。
           如果不剪枝的话肯定要超时,事实证明也确实是这样,第一次不信邪没有简直提交果断超时,然后简单的剪了一下,AC了。
           题目还是比较简单的,很容易理解,比之前做的HDU1010需要奇偶剪枝的容易了不知道多少倍~
           然后还有一个要注意的地方是输出,每输出一个测试数据就换一下行,不是每两组测试数据之间换行,之前也因为这个表达错误了一次。


AC代码:

#include<iostream>
#include<cstring>
using namespace std;

int cir[25], isFind[25];//isFind数组用来记录数是否已经被用过

bool isPrime(int n)//判断素数
{
	int i = 2;
	for (; i < n; i++)
	{
		if (n % i == 0) return 0;
	}
	return 1;
}

void dfs(int i, int n)
{
	if (i >= n)
	{
		if (isPrime(cir[n-1] + cir[0]))// 最后判断最后一个数字和第一个数字的和是不是素数
			for (int x = 0; x < n; x++)
				if(x != n -1) cout << cir[x] << " ";
				else cout << cir[x] << endl;		
	}
	int j;
	for (j = 2; j <= n; j++)
	{
		if (isFind[j]) continue;
		cir[i] = j;
		isFind[j] = 1;
		if ( !isPrime(cir[i - 1] + cir[i]) ) //判断当前数与之前一个数的和是不是素数, 不是就直接pass, 也就是剪枝
		{
			isFind[j] = 0;//如果不满足,就恢复数字的使用标记,进行下一次循环
			continue;
		}
		dfs(i + 1, n);
		isFind[j] = 0;// 恢复数字的使用标记
	}
}

int main()
{
	int n, i, count = 0;
	while (cin >> n)
	{
		cout << "Case " << ++count << ":" << endl;
		memset(cir, 0, sizeof(cir));
		memset(isFind, 0, sizeof(isFind));
		cir[0] = 1;//题目规定第一个数字必须是1
		dfs(1, n);//从i=1即第二个数字开始向下搜索
		cout << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值