题目描述:

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.

输入:

n (1 < n < 17).

输出:

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.

样例输入:
6
8
样例输出:
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

为了解决该问题,我们可以采用回溯法枚举每一个值。当第一个数位为1确定时,我们尝试放入第二个数,使其和1的和为素数,放入后再尝试放入第三个数,使其与第二个数的和为素数,直到所有的数全部被放入环中,且最后一个数与1的和也是素数,那么这个方案即为答案,输出;若在尝试放数的过程中, 发现当前位置无论放置任何之前未被使用的数均不可能满足条件,那么我们回溯 改变其上一个数,直到产生我们所需要的答案,或者确实不再存在更多的解。
#include "stdafx.h"
#include <stdio.h>
using namespace std; int prime[] = { , , , , , , , , , , , };
int number[];
bool hash[];
int n;
bool isPrime(int num)
{
for (int i = ; i < ;i++)
if (num == prime[i])
return true;
return false;
} void printArray()
{
if (isPrime(number[n] + number[]) == false)
return;
for (int i = ; i <= n; i++)
{
if (i != )
printf(" ");
printf("%d", number[i]);
}
printf("\n");
} void DFS(int num)
{
if (num > && isPrime(number[num] + number[num - ]) == false)
return;
if (num == n)
{
printArray();
return;
} for (int i = ; i <= n; i++)
{
if (hash[i] == false)
{
hash[i] = true;
number[num + ] = i;
DFS(num + );
hash[i] = false;
}
}
} int main()
{
int cas = ;
while (scanf("%d", &n) != EOF)
{
cas++;
for (int i = ; i < ; i++)
hash[i] = false;
number[] = ;
printf("Case %d:\n", cas);
hash[] = true;
DFS();
printf("\n");
} return ;
}

最新文章

  1. jquery ui 中的插件开发
  2. javascript设计模式之观察者模式
  3. nginx+uwsgi 部署 django
  4. 如何垂直居中一个&lt;img&gt;?
  5. 【干货分享】Node.js 中文资料导航
  6. vijosP1903学姐的实习工资
  7. Android调用第三方应用
  8. struts2整合json要注意的问题
  9. html常用的知识点以及混合框架
  10. CMDB服务器管理系统【s5day89】:采集资产之整合资产
  11. 北大poj- 1034
  12. Spark机器学习(2):逻辑回归算法
  13. sencha touch Button Select(点击按钮进行选择)扩展
  14. IntelliJ IDEA 阿里巴巴编码插件
  15. 简话Angular 08 Angular ajax
  16. Yii Model
  17. Nginx配置里的fastcgi_index和index
  18. C#连接SQL Server测试
  19. 洛谷P3726 [AH2017/HNOI2017]抛硬币(组合数+扩展Lucas)
  20. Eclipse中各图标含义

热门文章

  1. Linux下hosts、host.conf、resolv.conf的区别
  2. 《Effective Java》读书笔记三(类和接口)
  3. MarkDown的vim插件安装
  4. SQL 从查询结果里查询
  5. linux 日志定时轮询流程详解(logrotate)
  6. android framework-下载Android系统源代码
  7. Ubuntu 安装谷歌拼音输入法
  8. cjson库
  9. C#类的修饰符
  10. 【精】C# 中的委托和事件(转)