题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1016
题意:
输出所有满足 相邻两个数的和是素数的环。
题解:
运用dfs, 从1开始搜索, 只要满足和上一个数互质就存到数组里,终止条件为搜索了n-1次 并且 最后一个数加1是质数时输出,输出数组里所有数字。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
int ans[20 + 10];
int n;
bool not_contain(int num, int depth)
{
for(int i = 0; i <= depth; i++)
{
if(ans[i] == num)return false;
}
return true;
}
bool is_prime(int num)
{
int i = 2;
while(i <= num/2)
{
if(num % i == 0)
{
return false;
}
i++;
}
return true;
}
void dfs(int depth)
{
if(depth >= 0 && depth == n-1 && is_prime(ans[depth] + ans[0]))
{
for(int i = 0; i <= depth; i++)
{
if(i == depth)
{
printf("%d\n", ans[i]);
}
else{
printf("%d ", ans[i]);
}
}
}
for(int i = 1; i <= n; i++)
{
if(is_prime(ans[depth] + i) && not_contain(i,depth))
{
depth++;
ans[depth] = i;
dfs(depth);
ans[depth] = 0;
depth--;
}
}
}
int main()
{
int cnt = 1;
while(~scanf("%d", &n))
{
ans[0] = 1;
printf("Case %d:\n", cnt++);
dfs(0);
cout << endl;
}
return 0;
}