Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 27754 Accepted Submission(s): 12338
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.
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.
题意:找出一个数字环,使相邻的两个数字和为质数。注意输出时要打出一个空行。
#include <iostream>
using namespace std;
int n,res[25];
bool isok[25];
bool prime(int num)
{
for(int i=2;i<=sqrt(num+0.0);i++)
if(num%i==0)
return false;
return true;
}
void dfs(int cur)
{
if((cur==n)&&prime(res[n-1]+1))
{
for(int i=0;i<n-1;i++)
cout<<res[i]<<" ";
cout<<res[n-1]<<endl;
return;
}
if(cur==0)
{
res[0]=1;
isok[1]=true;
dfs(cur+1);
}
else
{
for(int i=1;i<=n;i++)
{
if(!isok[i]&&prime(i+res[cur-1]))
{
isok[i]=true;
res[cur]=i;
dfs(cur+1);
isok[i]=false;
}
}
}
}
int main()
{
int cnt=1;
while(cin>>n)
{
cout<<"Case "<<cnt++<<":"<<endl;
for(int i=0;i<25;i++)
isok[i]=false;
dfs(0);
cout<<endl;
}
}
这是我写的第一个搜索程序,写完挺激动←_←