HDU 1016 Prime Ring Problem
来源:互联网 发布:开淘宝店的准备工作 编辑:程序博客网 时间:2024/06/04 00:26
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 49304 Accepted Submission(s): 21745
Total Submission(s): 49304 Accepted Submission(s): 21745
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.
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 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.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
68
Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
本题题意:
给你n个数让你用从1—n的n个数围成一个环,使相邻两个数之和为素数。
解题思路:
用回溯法搜索,深度优先搜索。
注意:
注意题目的输出格式,因为格式错误WA了好几遍呢!!!
代码:
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>#include <queue>using namespace std;int n;int a[25],vis[25];bool sushu(int n)///判断素数{ if(n<2) return false; for(int i=2; i*i<=n; i++) { if(n%i==0) return false; } return true;}void dfs(int s){ if(s==n&&sushu(a[1]+a[n]))///边界条件 { for(int i=1; i<n; i++) { cout<<a[i]<<" "; } cout<<a[n]<<endl; } else { for(int i=2; i<=n; i++) { if(!vis[i]&&sushu(i+a[s]))///如果i未被用过,并与前一个数之和为素数 { a[s+1]=i; vis[i]=1;///标记 dfs(s+1);///深搜 vis[i]=0;///重置标记数组 } } }}int main(){ int t=0;///记录情况数 while(scanf("%d",&n)!=EOF) { memset(vis,0,sizeof(vis)); a[1]=1; t++; cout<<"Case "<<t<<":"<<endl; dfs(1); cout<<endl;///每种情况下打印一行空白行 } return 0;}
3 0
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- HDU 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- HDU-1016 prime ring problem
- hdu 1016Prime Ring Problem
- hdu 1016 Prime Ring Problem
- HDU-1016 Prime Ring Problem
- HDU-1016-Prime Ring Problem
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- Hdu 1016 Prime Ring Problem
- hdu 1016 Prime Ring Problem
- Hdu 1016 - Prime Ring Problem
- HDU 1016 Prime Ring Problem
- 3.3 JS 表单自动获得焦点&&鼠标经过全选表单内容
- 算法笔记(III) 状态空间搜索
- 系统学习javaweb-12-SSH整合开发demo
- 单线激光雷达在自动驾驶中的原理?
- JAVA 学习第1天
- HDU 1016 Prime Ring Problem
- js闭包与for循环
- IDEA 创建文件夹总默认根节点问题解决
- spring boot 整合 druid + Mysql + Mybatis
- JavaWeb报错:The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
- java.util.Timer
- excel
- requirejs基本用法
- Return of the Nim