HDU-1016 Prime Ring Problem
来源:互联网 发布:exe一机一码加密软件 编辑:程序博客网 时间:2024/06/01 08:46
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
主要思路:回溯法
C++代码:
#include<iostream>using namespace std;int prime(int num){ if(num==1) return 0; if(num==2) return 1; for(int i=2;i<=num-1;i++) if(num%i==0) return 0; return 1;}int different(int k,int *x){ for(int i=1;i<k;i++) if(x[k]==x[i]) return 0; return 1;}int place(int k,int n,int *x){ for(int i=1;i<k;i++) if(!prime(x[k]+x[k-1])||!different(k,x)) return 0; return 1;}void traceback(int k,int n,int *x){ if(k>n){ if(prime(x[n]+x[1])){ cout<<x[1]; for(int i=2;i<=n;i++) cout<<" "<<x[i]; cout<<endl; } } else{ for(int i=1;i<=n;i++){ x[k]=i; if(place(k,n,x)) traceback(k+1,n,x); } }}int main(){ int n=1,*x; int count=0; while(cin>>n){ count++; cout<<"Case "<<count<<":"<<endl; x=new int[n+1]; for(int i=0;i<=n;i++) x[i]=0; x[1]=1; traceback(2,n,x); cout<<endl; } return 0;}
注意:输出格式很重要,Presentation Error很扎心!
- 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
- C++学习整理(关联容器与动态内存)
- 数字图像基本处理算法
- 模p平方根算法实现
- 洛谷 2420 让我们异或吧
- CCF 图像旋转
- HDU-1016 Prime Ring Problem
- 贪心算法——单源最短路径(Dijkstra算法)
- 关于Ajax的跨域问题
- Struts2自定义拦截器
- Mybatis多环境数据源配置方式之environment标签
- Java 多线程并发编程之互斥锁 Reentrant Lock
- Android TP 驱动之(一)I2C
- HDU 4908 BestCoder Sequence 思维
- SDUT-3345 数据结构实验之二叉树六:哈夫曼编码