1333: 【例】【提高】素数环
内存限制:128 MB
时间限制:1.000 S
评测方式:文本比较
命题人:
提交:9
解决:8
题目描述
从1~n(2<=n<=10)这n个数,摆成一个环,要求相邻的两个数的和是素数,按照由小到大请输出所有可能的摆放形式。
比如:n = 4,输出形式如下
1:1 2 3 4
2:1 4 3 2
3:2 1 4 3
4:2 3 4 1
5:3 2 1 4
6:3 4 1 2
7:4 1 2 3
8:4 3 2 1
total:8
比如:n = 6,输出形式如下
1:1 4 3 2 5 6
2:1 6 5 2 3 4
3:2 3 4 1 6 5
4:2 5 6 1 4 3
5:3 2 5 6 1 4
6:3 4 1 6 5 2
7:4 1 6 5 2 3
8:4 3 2 5 6 1
9:5 2 3 4 1 6
10:5 6 1 4 3 2
11:6 1 4 3 2 5
12:6 5 2 3 4 1
total:12
输入
一个整数n(2<=n<=10)
输出
前若干行,每行输出一个素数环的解,最后一行,输出解的总数
样例输入 复制
4
样例输出 复制
1:1 2 3 4
2:1 4 3 2
3:2 1 4 3
4:2 3 4 1
5:3 2 1 4
6:3 4 1 2
7:4 1 2 3
8:4 3 2 1
total:8
提示
#include<bits/stdc++.h>
using namespace std;
#define N 20
int n,cnt=0;int path[N];bool used[N];
void print(){
cout<<cnt<<':';
for(int i=1;i<=n;i++){
cout<<path[i]<<' ';
}
cout<<endl;
}
bool isPrime(int x){
for(int i=2;i<=sqrt(x);i++){
if(x%i==0) return false;
}
return true;
}
void dfs(int x){
if(x>n){
if(isPrime(path[n]+path[1])){
cnt++;
print();
}
return;
}
for(int i=1;i<=n;i++){
if(!used[i]&&(x==1||isPrime(path[x-1]+i))){
path[x]=i;
used[i]=true;
dfs(x+1);
used[i]=false;
}
}
}
int main(){
cin>>n;
dfs(1);
cout<<"total:"<<cnt;
return 0;
}