设为首页 加入收藏

TOP

HDU1016 Prime Ring Problem(深度优先搜索)
2015-07-20 17:30:41 来源: 作者: 【 】 浏览:4
Tags:HDU1016 Prime Ring Problem 深度 优先 搜索

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 27488 Accepted Submission(s): 12248

Problem Description 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.

\

Input n (0 < n < 20).

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 Z??http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcmRlciBvZiBudW1iZXJzIG11c3Qgc2F0aXNmeSB0aGUgYWJvdmUgcmVxdWlyZW1lbnRzLiBQcmludCBzb2x1dGlvbnMgaW4KIGxleGljb2dyYXBoaWNhbCBvcmRlci48YnI+Cjxicj4KWW91IGFyZSB0byB3cml0ZSBhIHByb2dyYW0gdGhhdCBjb21wbGV0ZXMgYWJvdmUgcHJvY2Vzcy48YnI+Cjxicj4KUHJpbnQgYSBibGFuayBsaW5lIGFmdGVyIGVhY2ggY2FzZS48YnI+CgoKPGJyPgpTYW1wbGUgSW5wdXQKCjxwcmUgY2xhc3M9"brush:java;">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
问题描述:将从1到n这n个整数围成一个圆环,若其中任意2个相邻的数字相加,结果均为素数,那么这个环就成为素数环。 n=20时,下面的序列就是一个素数环: 1 2 3 4 7 6 5 8 9 10 13 16 15 14 17 20 11 12 19 18
思路如下: 对除奇数个以外的20以内的所有情况进行筛选,若能同时满足相邻相加为素数,且保证在数组中第一次使用则可选,向下继续搜索。关于素数的判断,建议提前打表,节约时间啊有木有。。。
#include
  
   
#include
   
     using namespace std; int t[21]; int pre[20]; int N,count; int prime(int m) { int x=(int)sqrt((double)m); for(int k=2;k<=x;k++) { if(m%k==0) return 0; } return 1; } int judge(int m) { for(int i=1;i<=N&&t[i]!=0;i++) { if(m==t[i]) return 0; } return 1; } int prim(int m) { for(int i=0;i<20;i++) if(m==pre[i])return 1; return 0; } void DFS(int n) { if(n==N+1) { if(prime(t[N]+t[1])) { for(int k=1;k
    
     >N&&N%2==0) { count++; cout<<"Case "<
     
      
之后看了一个别人的,发现也是不错的哦,时间和空间上都有很大的优化。
#include"stdio.h"
#include"string.h"
int n;
int a[123],used[123];
int ok(int n)
{
    int i;
    for(i=2;i
       
        这里注意,used数组是用来标记已被选用的i值,而a数组则是从0开始存储依次选取的数值,这也正解决了一个数组无法使用标记搜索。						
       
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇BZOJ 1091([SCOI2003]切割多边形-.. 下一篇BZOJ 3037 创世纪 树形DP

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C++ Lambda表达式保 (2025-12-26 05:49:45)
·C++ Lambda表达式的 (2025-12-26 05:49:42)
·深入浅出 C++ Lambda (2025-12-26 05:49:40)
·C语言指针从入门到基 (2025-12-26 05:21:36)
·【C语言指针初阶】C (2025-12-26 05:21:33)