您的位置:首页 > 其它

HDU 1016 Prime Ring Problem

2014-04-11 00:30 330 查看
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1016

暴力DFS,无剪枝,如判素数优化。

#include<iostream>
#include<cmath>
using namespace std;

int N;
int num[25];

bool judge(int n)
{
int mark=1;
double temp=sqrt((double)n);
for(int i=2;i<=temp;i++)
{
if(n%i==0)
{
mark=0;
break;
}
}
if(mark)
return true;
else
return false;
}

void DFS(int n)
{
int i,j;
if(n>N)
{
for(i=1;i<N;i++)
cout<<num[i]<<" ";
cout<<num
<<endl;
}
else
{
for(i=1;i<=N;i++)
{
int ok=1;
num
=i;
for(j=1;j<n;j++)
{
if(n!=N)
{
if(!judge(num
+num[n-1])||num
==num[j])
{
ok=0;
break;
}
}
else
{
if(!judge(num
+num[n-1])||num
==num[j]||!judge(num
+num[1]))
{
ok=0;
break;
}
}
}
if(ok)
DFS(n+1);
}
}
}

int main()
{
int T=1;
while(cin>>N)
{
cout<<"Case "<<T<<":"<<endl;
num[1]=1;
DFS(2);
T++;
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  DFS