Description
Note: the number of first circle should always be 1.
![](https://i-blog.csdnimg.cn/blog_migrate/427b1dd2282412709d583cc17eda983e.gif)
Input
Output
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,要构成一个素数环,这个素数由1-n组成,它的特征是选中环上的任意一个数字i,i与它相连的两个数加起来都分别为素数,满足就输出。
解题思路
dfs深搜全部的搜索一遍就行,也可以将素数全部打表记录,可以一定程度的节省时间
源代码
#include<iostream>
#include<cmath>
#include<algorithm>
#include<string.h>
#include<cstring>
using namespace std;
int vis[21],maze[21];
int n,k=1;
bool pri(int a,int b)
{
int c=a+b;
for (int i=2;i<=sqrt(c);++i)
{
if (c%i==0)
return false;
}
return true;
}
void DFS(int cur)
{
if (cur==n&&pri(1,maze[n-1]))
{
cout<<maze[0];
int i;
for(i=1;i<n;++i)
{
cout<<' '<<maze[i];
}
cout<<endl;
}
else
{
int i;
for (i=2;i<=n;++i)
{
if(true==vis[i]||!pri(maze[cur-1],i))
{
continue;
}
maze[cur]=i;
vis[i]=true;
DFS(cur+1);
vis[i]=false;
}
}
}
int main()
{
maze[0]=1;
memset(vis,false, sizeof(vis));
while (cin>>n)
{
cout<<"Case "<<k++<<':'<<endl;
DFS(1);
cout<<endl;
}
return 0;
}