素数环
问题 E: 素数环 [ 提交 ][ ״̬ ][ 讨论版 ][命题人: quanxing ] 题目描述 素数环:从1到n这n个数摆成一个环,要求相邻的两个数的和是一个素数。如,n=8是,素数环为: 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 总数为4 输入 输出 样例输入 8 样例输出 4 解题思路:回溯搜索,开一个num数组用于保存素数环中的数,一个mk[i]数组用于标记数值为i的数是否已经在素数环中,然后dfs一下即可 #include<iostream> #include<cstring> #include<algorithm> using namespace std; int n,sum=0; int num[16],mk[16]; int j=2; bool is_Ok(int x,int y)//判断相邻俩个数的和是否为素数 { int sum=x+y; int j=sqrt(sum); for(int i=2;i<=j;++i) { if(sum%i==0)return false; } return true; } void dfs(int x) { if(x>n) { if(is_Ok(num[1],num[n]))sum++;//如果每一个数都已经存入素数环中