HDU1016 Prime Ring Problem(素数环)

题目链接

Prime Ring Problem

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

 

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

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

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

clockwisely    顺时针地

anticlockwisely  逆时针地

lexicographical  字典序地

比较典型的dfs。注意格式要求,每一组的最后一个数据后面没有空格。

AC代码:

#include<iostream>
#include<sstream>
#include<algorithm>
#include<string>
#include<cstring>
#include<iomanip>
#include<vector>
#include<cmath>
#include<ctime>
#include<stack>
using namespace std;
int N,a[21],book[21];
bool isprime(int n)//n是否为素数 
{
	if(n==2||n==3) return 1;
	if(n%6!=1&&n%6!=5) return 0;
	int b=sqrt(n);
	for(int i=5;i<=b;i+=6)
	    if(n%i==0||n%(i+2)==0) return 0;
	return 1;
}
void dfs(int step)
{
	if(step==N+1)
	{
		if(isprime(a[1]+a[N]))
		{
			for(int j=1;j<=N;j++)
			if(j!=N) cout<<a[j]<<' ';
			else cout<<a[j];
			cout<<endl;
		}
                return;
	}
	for(int i=2;i<=N;i++)
	{
		if(book[i]) continue;
		if(isprime(i+a[step-1])) 
		{
			book[i]=true;
			a[step]=i;
			dfs(step+1);
			book[i]=false;//回溯 
		}
	}
}
int main()
{
	int count=1;
	while(cin>>N)
	{
		memset(book,0,sizeof(0));
		a[1]=1;
		cout<<"Case "<<count++<<":\n";
		dfs(2);
                cout<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40889820/article/details/82596808