您的位置:首页 > 其它

相邻数字相加为质数

2015-07-30 20:16 281 查看
题意:

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers

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 <= 16)

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.

You are to write a program that completes above process.

Sample Input

6
8


Sample Output

Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2


思路分析:

哈!DFS!

1、可以从第二个数开始放(题目要求第一个数为1),每次放一个数要跟前面的数相加,判断是否为质数。

是:标记该数已经用过,可以继续往下放

否:撤销标记,回溯上一个数

2、判断越界:数字都用完了&&最后一个数跟第一个数相加也是一个质数

源代码:

#include<iostream>
#include<cstring>
using namespace std;
int n;
int pri[11] = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };    //质数表
int ans[20];              //储存给的数
int used[20];            //用来标记用过的数
int is_pri(int a, int b)            //判断相加是否是质数
{
int w = 0;
for (int i = 0; i < 10; i++)
{

if (a + b == pri[i])

return 1;
}
return 0;
}
void dfs(int a)
{

if (a == n && is_pri(ans[0], ans[n - 1]))        //结束条件
{
for (int i = 0; i < n; i++)
{

if (i == n - 1)
{
cout << ans[i];        //最后一个单独输出,要求格式。
break;
}
cout << ans[i] << " ";
}cout << endl;
}
else

for (int i = 2; i <= n; i++)
if (!used[i] && is_pri(i, ans[a - 1]))
{
used[i] = 1;            //该数已经使用
ans[a] = i;             //把i放进a位置
dfs(a + 1);
used[i] = 0;            //清除使用记录(不满足的数)
}
}
int main()
{

memset(ans, 0, sizeof(ans));
memset(used, 0, sizeof(used));
ans[0] = 1;                       //题目要求,第一个数要为1.
int count = 0,k=0;
while (cin >> n)
{
if (k++)
cout << endl;
count++;
if (n == 0)
return 0;

printf("Case %d:\n", count);
dfs(1);

}

return 0;
}


心得:

瞬间发现DFS的题就是按照模板在做题。。。。嗯,细节还是要注意的!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: