hdu1016素数环(dfs)

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

运用一下dfs,注意点细节就好了,直接看代码吧

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <cstdlib>
#include <queue>
#include<iomanip>
using namespace std;
int p[25], ji[25],m,q[50],j=1;p记该路线的第I个填的数字;
void dfs(int step)
{
	if (step == m&&q[p[1]+p[m]])//行大运将数字填进圆圈里,但填好m个即填好了
	{
		
		for (int i = 1; i < m; i++)
			printf("%d ", p[i]);
		printf("%d\n", p[m]);
		
		return;
	}
	for (int i = 2; i <= m; i++)
	{
		if (!ji[i] && q[p[step] + i])//相邻两个数字加起来是素数且该数字在该路线还未用到,即可填入该路线
		{
			p[step + 1] = i;
			ji[i] = 1;
			dfs(step + 1);
			ji[i] = 0;//在另一路线,该数字未填入,给初始化。
		}
	}

}
int main()
{
	while (cin >> m)
	{
	
		memset(ji, 0, sizeof(ji));
		memset(q, 0, sizeof(q));
		q[2] = q[3] = q[5] = q[7] = q[11] = q[13] = q[17] = q[19] =q[23]=q[29]=q[31]=q[37]= 1;//将素数的标记一下
		ji[1] = 1; p[1] = 1;
		cout << "Case " << j << ":" << endl;
		dfs(1);
		printf("\n");
		j++;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43965698/article/details/87127619
今日推荐