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.

 

Inputn (0 < n < 20). 
OutputThe 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. 
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 思路:依旧是回溯法,逐个判断即可,注意首尾也需要判断一下,用筛法建个表,代码如下:
const int maxm = ;

int n, vis[maxm], prime[], res[maxm], kase = ;

void buildTable() {
for (int i = ; i * i < ; ++i) {
if(!prime[i]) {
for (int j = i * i; j < ; j += i)
prime[j] = ;
}
}
} void dfs(int i) {
if(i == n && !prime[res[] + res[n-]]) {
for (int j = ; j < n; ++j) {
if(j)printf(" ");
printf("%d", res[j]);
}
printf("\n");
}
for (int j = ; j <= n; ++j) {
if(!vis[j] && !prime[res[i-] + j]) {
vis[j] = ;
res[i] = j;
dfs(i + );
vis[j] = ;
}
}
} int main() {
buildTable();
while(scanf("%d",&n) != EOF) {
printf("Case %d:\n", ++kase);
memset(vis, , sizeof(vis));
res[] = ;
vis[] = ;
dfs();
printf("\n");
}
return ;
}

最新文章

  1. 50个新的汉化Demo!纯前端 Wijmo 放大招
  2. JSON 获取属性值的方法
  3. [翻译]深度学习的机器(The&#160;learning&#160;machines)
  4. Gartner:Hype Cycle for Emerging Technologies-2013
  5. CURL 宏定义列表
  6. IOS系统对fixed定位支持不好的解决方法
  7. 三篇IMO的文章
  8. Openstack &amp;amp; Hadoop结合项目Sahara
  9. Oracle dual表的用途
  10. C-C++到底支不支持VLA以及两种语言中const的区别
  11. F和弦大横按
  12. hdu 5538(水)
  13. JMM
  14. RomUtil【Android判断手机ROM,用于判断手机机型】
  15. shell编程 之 传递参数到脚本里
  16. Python语法注意点
  17. js里面关于日期转换的问题
  18. python函数之第一类对象
  19. C# json字符串转为对象
  20. Go之简单并发

热门文章

  1. Perl 笔记
  2. Spring Boot Web 开发@Controller @RestController 使用教程
  3. Linux下运行SuperSocket记录
  4. Codeforces Round #611 (Div. 3) D
  5. 杭电2504 又见GCD
  6. Asteroids!_poj2225
  7. BlockingQueue的几个实现分析
  8. 通过view获取所在的viewController对象
  9. P1025数的划分
  10. Educational Codeforces Round 72 (Rated for Div. 2)E(线段树,思维)