hdu 1016 Prime Ring Problem(深度优先搜索)

时间:2023-12-17 13:50:38

Prime Ring Problem

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

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.
hdu 1016 Prime Ring Problem(深度优先搜索)
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 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的组合,使得相邻两个数之和为素数;
分析:预处理40之间的素数,然后回溯;
 #include<iostream>
#include<cstring>
#define N 25
#define M 40
using namespace std; bool is_prime[M],visited[N];
int n,test,ans[N]; void work(int k)
{
int i;
if(k==n+)
{
if(!is_prime[ans[n]+ans[]]) return ;
for(i=;i<=n-;i++)
cout<<ans[i]<<" ";
cout<<ans[i]<<endl;
return ;
}
for(i=;i<=n;i++)
{
if(!visited[i]&&is_prime[ans[k-]+i])
{
visited[i]=true;
ans[k]=i;
work(k+);
visited[i]=false;
}
}
} bool prime(int n)
{
if(n==) return false;
if(n==||n==) return true;
int i;
for(i=;i<n;i++)
if(n%i==)
return false;
return true;
} int main()
{
int i;test=;
for(i=;i<M;i++) is_prime[i]=prime(i);
while(cin>>n)
{
ans[]=;
memset(visited,false,sizeof(visited));
cout<<"Case "<<test<<":"<<endl;
work();
test++;
cout<<endl;
}
return ;
}