素数环
题目链接:https://www.luogu.com.cn/problem/solution/UVA524
题意:
按1逆时针排列构成的环每个数+左边或右边的数构成素数,输出排列
题意:
经典大法师,思路是用静态数组A模拟,递归压栈cur,重点是不能取重以及回溯
#include<bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define pb push_back
#define endl "\n"
#define fi first
#define se second
//#pragma GCC optimize(3)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef __int128 lll;
typedef pair<int,int> pii;
const int inf=0x3f3f3f3f;
const ll llmax=LLONG_MAX;
const int maxn=1e5+5;
const int mod=1e9+7;
int a[50];
unordered_set<int>prime;
bool p[maxn];
bool v[50];
int n;
void e(){
for(int i=2;i<=50;i++){
if(!p[i]){
prime.insert(i);
for(int j=i*i;j<=50;j+=i)p[j]=true;
}
}
}
void dfs(int cur){
if(cur==n+1&&prime.count(a[n]+a[1])){
for(int i=1;i<=n-1;i++){
cout<<a[i]<<' ';
}
cout<<a[n];
cout<<endl;
return;
}
for(int i=2;i<=n;i++){
if(!v[i]&&prime.count(a[cur-1]+i)){
a[cur]=i;
v[i]=true;
dfs(cur+1);
v[i]=false;
}
}
}
void solve(){
a[1]=1;
e();
int k=1;
while(scanf("%d",&n)!=EOF){
if(k>=2)cout<<endl;
cout<<"Case "<< k++ <<':'<<endl;
dfs(2);
}
}
signed main()
{
int T=1;
while(T--){
solve();
}
return 0;
}

浙公网安备 33010602011771号