您的位置:首页 > 其它

HDOJ-1016 Prime Ring Problem 素数环 DFS

2016-02-27 15:26 351 查看

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;
}
}


这是我写的第一个搜索程序,写完挺激动←_←
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: