Prime Ring Problem
来源:互联网 发布:seo知否 编辑:程序博客网 时间:2024/06/06 23:51
题目链接
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 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
#include<iostream>#include<cstring>#include<cstdio>#include<cmath>using namespace std;int n, dis[20];bool visited[20];bool is_Prime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true;}void dfs(int a){ if(a == n && is_Prime(1+dis[n-1])){//如果到达结尾,并且最后一个数和第一个数1能够构成素数 for(int i = 0; i < n; i++){ if(!i) cout<<dis[i]; else cout<<" "<<dis[i]; } cout<<endl; return; } else for(int i = 2; i <= n; i++) if(!visited[i] && is_Prime(i+dis[a-1])){ visited[i] = true; dis[a] = i; dfs(a + 1); visited[i] = false; }}int main(){ int sign = 1; while(cin>>n){ cout<<"Case "<<sign++<<":"<<endl; if(n == 1){//一个数字也可以构成环 cout<<"1"<<endl; continue; } if(n&1){//&1的结果就是取二进制的最末位t,t==1是奇数,t==0为偶数 /* 奇数不行的原因是: 1.奇数+奇数 = 偶数(不是质数) 2.奇数+偶数 = 奇数(不能确定是否是质数) 3.偶数+偶数 = 偶数(不是质数) ps:如果n是奇数的话,定会导致奇数的个数比偶数的个数多一个 换句话说,只有奇数和偶数一一对应的时候,才有可能出现质数,即奇数的个数==偶数的个数 */ cout<<"No Answer"<<endl; continue; } dis[0] = 1; memset(visited,false, sizeof(visited)); dfs(1); cout<<endl; } return 0;}
- 1016 Prime Ring Problem
- HDOJ1016-Prime Ring Problem
- HDU1016 Prime Ring Problem
- DFS__1195: Prime Ring Problem
- Prime Ring Problem
- 1016:Prime Ring Problem
- 1016 Prime Ring Problem
- HDUOJ1016 Prime Ring Problem
- 1016 Prime Ring Problem
- Prime Ring Problem
- hdu1016 Prime Ring Problem
- Prime Ring Problem(dfs)
- Prime Ring Problem
- Prime Ring Problem
- Prime ring problem
- hdu1016-Prime Ring Problem
- HDU1035 Prime Ring Problem
- 1016Prime Ring Problem
- 软件测试常见测试点
- SSH 保持连接
- 段错误
- JS组件系列——BootstrapTable 行内编辑解决方案:x-editable
- 禁用Microsoft Compatibility Telemetry
- Prime Ring Problem
- iOS和安卓与JS交互之JS
- session
- vim处理字符的大小写转换
- 白盒测试教程基础大纲
- @RequestMapping 用法详解之地址映射(转)
- Uva 11468 Substring——AC自动机+概率DP
- 分析生产和库存,靠这一套指标就够了!
- 苹果开发者账号全解-关于申请开发者账号的所有答案