HDU - 1016 Prime Ring Problem【dfs】

Prime Ring Problem

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

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

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016

扫描二维码关注公众号,回复: 5392786 查看本文章

简述:给出一个由n个数(1~n)组成的环,相邻两个数之和是素数,按顺序输出。

分析:将环化为数组,第0个数是1,后面每一个数与前一个数之和是素数且最后一个数与1之和为素数。写一个bool类型函数判断素数,dfs函数进行深搜。。。

说明:第0个数永远是1,记得递归边界且最后一个数跟第一个数之和也为素数。

AC代码如下:

#include <iostream>
#include <cstring>
using namespace std;
int n, t=1;
int a[20], vis[20] = {0};
bool sushu(int a)
{
	int i;
	if (a == 1) return false;
	if (a == 2) return true;
	for (i = 2; i*i <= a; i++)
	{
		if (a%i == 0) return false;
	}
	return true;
}
void dfs(int b)
{
	int i;
	if (b == n && sushu(a[n-1] + 1)) //递归边界
	{
		cout << a[0];
		for (i = 1; i < n; i++)
		{
			cout << " " << a[i];
		}
		cout << endl;
	}
	else
	{
		for (i = 2; i <= n; i++)
		{
			if (sushu(a[b - 1] + i) && vis[i] != 1) //没有被搜过,且与前一位之和是素数(前一位已经确定好了)
			{
				a[b] = i; //储存
				vis[i] = 1; //标记被搜过
				dfs(b + 1); //搜下一位,此处有无限次循环
				vis[i] = 0;
			}
		}
	}
}
int main()
{
	a[0] = 1; //第0个位置永远是1
	while (cin >> n)
	{
		memset(vis, 0, sizeof(vis)); //将数组清零
		cout << "Case " << t++ << ":" << endl;
		dfs(1);
		cout << endl;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_43966202/article/details/86691182
今日推荐