http://acm.hdu.edu.cn/showproblem.php?pid=1016简单的深搜,要求不重复,设置一个visit数组进行标记,设置result数组进行存储结果。注意dfs后,要重新将visit[i]置0。
#include <iostream>
#include <algorithm>
using namespace std;
int result[20];
bool isprime[]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0},visit[20];
int n;
void dfs(int step)
{
int i;
if(step==n+1)
{
if(isprime[result[n]+1])
for(i=1;i<=n;i++)
printf("%d%c",result[i],i==n?'\n':' ');
return ;
}
for(i=2;i<=n;i++)
if(!visit[i] && isprime[i+result[step-1]])
{
result[step]=i;
visit[i]=1;
dfs(step+1);
visit[i]=0;
}
}
int main()
{
int count=1;
while(cin>>n)
{
memset(visit,0,sizeof(visit));
result[1]=1;
cout<<"Case "<<count++<<":\n";
dfs(2);
cout<<endl;
}
return 0;
}
posted on 2011-04-07 07:04
大大木马 阅读(556)
评论(0) 编辑 收藏 引用